简体   繁体   English

如何使用php始终显示少于2位的int数?

[英]How to always show less than 2 position int number using php?

How to always show less than 2 position int number using php ? 如何始终使用php显示少于2个位置的int数?

This below code 这下面的代码

<?PHP
for($i=0;$i<=100;$i++)
{
echo $i."<BR>";
}
?>

result will be like this 结果将是这样

0
1
2
3
4
5
6
7
8
9
10
.
.
.
100

I want to always show less than 2 position int number. 我想始终显示少于2位的int数。 like this how can i apply my php code ? 像这样我如何应用我的PHP代码?

01
02
03
04
05
06
07
08
09
10
.
.
.
100

Just paste the lines inside your loop 只需将线粘贴到循环中

if ($i < 10) {
$i= str_pad($i, 2, "0", STR_PAD_LEFT);
}

And print $i. 并打印$ i。

I don't know for sure if this works, but you can try it like this: 我不确定这是否可行,但您可以这样尝试:

for($i=0;$i<=100;$i++)
{
    if($i < 10) {
        $i = "0$i";
        echo $i;
    }
    else {
        echo $i."<BR>";
    }
}

You can use the function sprintf or the function str_pad like this ... 您可以像这样使用函数sprintf或函数str_pad ...

<?PHP
    for ($i = 0; $i <= 100; $i++)
    {
        echo sprintf('%02d', $i) . "<BR>";
    }
?>

... or this ... ... 或这个 ...

<?PHP
    for ($i = 0; $i <= 100; $i++)
    {
        echo str_pad($i, 2, '0', STR_PAD_LEFT) . "<BR>";
    }
?>

Credits: https://stackoverflow.com/a/1699980/5755166 积分: https : //stackoverflow.com/a/1699980/5755166

You could checkout the sprintf function that allows you to format the output http://php.net/manual/en/function.sprintf.php 您可以签出sprintf函数,该函数可让您格式化输出http://php.net/manual/en/function.sprintf.php

Something like this perhaps 像这样的东西

echo sprintf("%'.02d\n", 1);

You can use str_pad for adding 0's: 您可以使用str_pad添加0:

str_pad($var, 2, '0', STR_PAD_LEFT); 

The 0 will not be added if the length is greater or equal 2. 如果长度大于或等于2,则不会添加0。

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

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