我需要在 php 中添加数字而不更改数字格式,如下所示
$a = "001";
$b = "5";
$c = $a+$b;
现在结果就像“6”,但如果我需要“006”$a
是“01”那么结果应该是“06”。
Thanks
从技术上来说,$a
and $b
在你的例子中是strings http://php.net/manual/en/language.types.string.php- 当您对它们使用加法运算符时,它们会转换为integers http://php.net/manual/en/language.types.integer.php它不能保留前导零。更多的有关字符串到数字转换的详细信息请参阅手册 http://php.net/manual/en/language.types.string.php#language.types.string.conversion
像这样的东西就可以做到(假设带有前导零的正整数字符串)
#figure out how long the result should be
$len=max(strlen($a), strlen($b));
#pad the sum to match that length
$c=str_pad($a+$b, $len, '0', STR_PAD_LEFT);
如果您始终知道字符串必须有多长,则可以使用sprintf http://php.net/sprintf, e.g.
$c=sprintf('%03d', $a+$b);
Here, %
引入一个占位符,03
告诉它我们希望用零填充来填充至少 3 位数字,并且d
告诉它我们正在格式化一个整数。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)