String numbers into number numbers in PHP

∥☆過路亽.° 提交于 2019-12-02 18:36:19

问题


How come when I set 00 as a value like this:

$var = 00;

it ouputs as 0 when I use it? How can I set 00 so that $var++ would become 01?


回答1:


Numbers in PHP (and virtually all languages) are not stored internally with leading (or in the case of decimal values, trailing) zeros.

There are many ways to display your numeric variables with leading zeros In PHP. The simplest way is to convert your value to a string, and pad the string with zero's until it's the correct length. PHP has a function called str_pad to do this for you:

$var = 0;
$var += 1;

// outputs '01'
echo str_pad($var, 2, '0', STR_PAD_LEFT);

Alternatively, the sprintf family of functions have a specifier for printing zero-padded values:

$var = 1;

// outputs '01'
printf("%02d", $var);



回答2:


Using a function like printf or sprintf will do this much more easily for you.

$number = 1;
printf("%02d", $number); // Outputs 01

$number = 25;
printf("%02d", $number); // Outputs 25

You can set the minimum width by replacing the two with another number.




回答3:


Also number_format() is your friend in formatting numbers.

http://php.net/manual/en/function.number-format.php

Great for ensuring there are 2 decimals for example.



来源:https://stackoverflow.com/questions/3963271/string-numbers-into-number-numbers-in-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!