【问题标题】:Zero-pad digits in string字符串中的零填充数字
【发布时间】:2010-09-24 08:57:14
【问题描述】:

我需要将单个数字(1 到 9)转换为(01 到 09)。我能想到一种方法,但它又大又丑又麻烦。我相信一定有一些简洁的方法。任何建议

【问题讨论】:

    标签: php


    【解决方案1】:

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

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

    更多信息请参考sprintf的文档。

    【讨论】:

    • @KonradRudolph 如果我将 digit 值作为整数传递,则该时间给出错误,如果作为字符串传递,则该时间没有问题
    • @HirenBhut 不,我 100% 确定它有效。文档是这样说的。我什至只为你测试过:gist.github.com/klmr/e1319f6d921a382e86296cce06eb7dbd
    • @KonradRudolph 请检查此代码gist.github.com/klmr/…
    • @HirenBhut 这完全不同,sprintf无关。检查format of integers,特别是关于八进制数字的部分。
    • @KonradRudolph 是的,有什么可能的解决方案吗?
    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

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

      【讨论】:

        【解决方案4】:

        str_pad 的性能很大程度上取决于填充的长度。要获得更一致的速度,您可以使用str_repeat

        $padded_string = str_repeat("0", $length-strlen($number)) . $number;
        

        还可以使用数字的字符串值以获得更好的性能。

        $number = strval(123);
        

        在 PHP 7.4 上测试

        str_repeat: 0.086055040359497   (number: 123, padding: 1)
        str_repeat: 0.085798978805542   (number: 123, padding: 3)
        str_repeat: 0.085641145706177   (number: 123, padding: 10)
        str_repeat: 0.091305017471313   (number: 123, padding: 100)
        
        str_pad:    0.086184978485107   (number: 123, padding: 1)
        str_pad:    0.096981048583984   (number: 123, padding: 3)
        str_pad:    0.14874792098999    (number: 123, padding: 10)
        str_pad:    0.85979700088501    (number: 123, padding: 100)
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2018-11-14
          • 2012-02-17
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-03-08
          • 2011-05-27
          相关资源
          最近更新 更多