为了账号安全,请及时绑定邮箱和手机立即绑定

字符串中的零填充数字

字符串中的零填充数字

PHP
临摹微笑 2019-11-13 16:02:05
我需要将单个数字(1到9)转换为(01到09)。我可以想到一种方法,但是它又大又丑又麻烦。我敢肯定必须有一些简洁的方法。有什么建议么
查看完整描述

3 回答

?
素胚勾勒不出你

TA贡献1827条经验 获得超9个赞

首先,您的描述具有误导性。Double是浮点数据类型。您大概想在字符串中用前导零填充数字。下面的代码可以做到这一点:


$s = sprintf('%02d', $digit);

有关更多信息,请参阅的文档sprintf。


查看完整回答
反对 回复 2019-11-13
?
慕勒3428872

TA贡献1848条经验 获得超5个赞

还有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_"

?>


查看完整回答
反对 回复 2019-11-13
?
紫衣仙女

TA贡献1839条经验 获得超15个赞

使用str_pad的解决方案:


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

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


查看完整回答
反对 回复 2019-11-13
  • 3 回答
  • 0 关注
  • 391 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信