String numbers into number numbers in PHP

丶灬走出姿态 提交于 2019-12-02 12:33:09

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

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.

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.

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