Kon*_*lph 205
首先,您的描述具有误导性.Double是浮点数据类型.你可能想要用字符串中的前导零填充你的数字.以下代码执行此操作:
$s = sprintf('%02d', $digit);
Run Code Online (Sandbox Code Playgroud)
有关更多信息,请参阅文档sprintf.
Lep*_*R64 86
还有str_pad
<?php
$input = "Alien";
echo str_pad($input, 10); // produces "Alien "
echo str_pad($input, 10, "-=", STR_PAD_LEFT); // produces "-=-=-Alien"
echo str_pad($input, 10, "_", STR_PAD_BOTH); // produces "__Alien___"
echo str_pad($input, 6 , "___"); // produces "Alien_"
?>
Run Code Online (Sandbox Code Playgroud)
Ale*_*lex 64
使用str_pad的解决方案:
str_pad($digit,2,'0',STR_PAD_LEFT);
Run Code Online (Sandbox Code Playgroud)
php 5.3的基准测试
结果str_pad:0.286863088608
结果sprintf:0.234171152115
码:
$start = microtime(true);
for ($i=0;$i<100000;$i++) {
str_pad(9,2,'0',STR_PAD_LEFT);
str_pad(15,2,'0',STR_PAD_LEFT);
str_pad(100,2,'0',STR_PAD_LEFT);
}
$end = microtime(true);
echo "Result str_pad : ",($end-$start),"\n";
$start = microtime(true);
for ($i=0;$i<100000;$i++) {
sprintf("%02d", 9);
sprintf("%02d", 15);
sprintf("%02d", 100);
}
$end = microtime(true);
echo "Result sprintf : ",($end-$start),"\n";
Run Code Online (Sandbox Code Playgroud)