简体   繁体   English

在php中添加两个数字并保留前导零

[英]Adding two numbers in php and retaining leading zeroes

I need to add numbers in php without changing the number format like below我需要在 php 中添加数字而不改变数字格式,如下所示

$a = "001";  
$b = "5";  
$c = $a+$b;  

Now the result comes like "6" but I need "006" if $a is "01" then the result should be "06".现在结果像“6”,但如果$a是“01”,我需要“006”,那么结果应该是“06”。

Thanks谢谢

Technically speaking, the $a and $b in your example are strings - when you use the addition operator on them they converted to integers which can't retain leading zeroes.从技术上讲,您示例中的$a$b字符串- 当您对它们使用加法运算符时,它们会转换为不能保留前导零的整数 More details on string-to-number conversion are in the manual有关字符串到数字转换的更多详细信息,请参见手册

Something like this would do it (assuming positive integer strings with leading zeros)像这样的事情会做到这一点(假设正整数字符串前导零)

#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);

If you always know how long the string has to be, you could use sprintf , eg如果你总是知道字符串有多长,你可以使用sprintf ,例如

$c=sprintf('%03d', $a+$b);

Here, % introduces a placeholder, 03 tells it we want zero padded to fill at least 3 digits, and d tells it we're formatting an integer.在这里, %引入了一个占位符, 03告诉它我们想要填充零以填充至少 3 位数字,而d告诉它我们正在格式化一个整数。

Hope this would help you:希望这会帮助你:

<?php
$a="001";
$b="5";
$l=max(strlen($a),strlen($b));
$c=str_pad($a+$b, $l,"0", STR_PAD_LEFT);
echo $c;
?>

For common case.对于普通情况。 Your code should looks like this.您的代码应如下所示。

$a = someFormat($original_a);
$b = someFormat2($original_b); // $b has different format.
$c = someFormat($a + $b);

Or, you need write formatRecognition function.或者,您需要编写 formatRecognition 函数。

$a = getValueA();
$b = getValueB();
$c = someFormat(formatRecognition($a), $a + $b);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM