且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将数字字符串转换为 PHP 中的数字

更新时间:2023-02-19 12:44:49

PHP(以及几乎所有语言)中的数字在内部存储时不带有前导(或在十进制值的情况下,尾随)零.

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

在 PHP 中有很多方法可以显示带前导零的数字变量.最简单的方法是将您的值转换为字符串,并用零填充字符串直到它的长度正确.PHP 有一个名为 str_pad 的函数来做这给你:

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

或者,sprintf 系列of 函数具有用于打印零填充值的说明符:

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

$var = 1;

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