字符串中的零填充数字

我需要将单个数字(1到9)转换为(01到09)。我可以想到一种方法,但是它又大又丑又麻烦。我敢肯定必须有一些简洁的方法。有什么建议么



临摹微笑
浏览 398回答 3
3回答

素胚勾勒不出你

首先,您的描述具有误导性。Double是浮点数据类型。您大概想在字符串中用前导零填充数字。下面的代码可以做到这一点:$s = sprintf('%02d', $digit);有关更多信息,请参阅的文档sprintf。

慕勒3428872

还有str_pad<?php$input = "Alien";echo str_pad($input, 10);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // produces "Alien&nbsp; &nbsp; &nbsp;"echo str_pad($input, 10, "-=", STR_PAD_LEFT);&nbsp; // produces "-=-=-Alien"echo str_pad($input, 10, "_", STR_PAD_BOTH);&nbsp; &nbsp;// produces "__Alien___"echo str_pad($input, 6 , "___");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;// produces "Alien_"?>

紫衣仙女

使用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++) {&nbsp; &nbsp; str_pad(9,2,'0',STR_PAD_LEFT);&nbsp; &nbsp; str_pad(15,2,'0',STR_PAD_LEFT);&nbsp; &nbsp; 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++) {&nbsp; &nbsp; sprintf("%02d", 9);&nbsp; &nbsp; sprintf("%02d", 15);&nbsp; &nbsp; sprintf("%02d", 100);}$end = microtime(true);echo "Result sprintf : ",($end-$start),"\n";
打开App,查看更多内容
随时随地看视频慕课网APP