【问题标题】:string to float and vice versa字符串浮动,反之亦然
【发布时间】:2012-11-11 05:45:15
【问题描述】:

如何将其转换为浮点数,然后递增,然后再转换回字符串。

if($set==$Data_Id)
{
$rel='1.1.1.2';
}

增量后应该是 1.1.1.3。

请帮忙。

【问题讨论】:

  • “1.1.1.3”在什么方面是单浮点数?你得到了三个“点”!
  • 请问您对 1.1.1.9 的期望是什么?

标签: php string increment


【解决方案1】:

太疯狂了,它可能会起作用

$rel='1.1.1.2';
echo substr($rel, 0, -1). (substr($rel,-1)+1); //1.1.1.3

最大的问题是如果字符串以 9 结尾,你想发生什么??

【讨论】:

    【解决方案2】:

    这里有一个稍微不同的方法。

    <?php
    function increment_revision($version) {
        return preg_replace_callback('~[0-9]+$~', function($match) {
            return ++$match[0];
        }, $version);
    }
    
    echo increment_revision('1.2.3.4'); //1.2.3.5
    

    安东尼。

    【讨论】:

      【解决方案3】:

      “1.1.1.2”不是有效数字。所以你必须做这样的事情:

      $rel = '1.1.1.2';
      $relPlusOne = increment($rel);
      function increment($number) {
          $parts = explode('.', $number);
          $parts[count($parts) - 1]++;
          return implode('.', $parts);
      }
      

      【讨论】:

      • 谢谢,我从你的代码中得到了逻辑,我已经用我的代码实现了,它工作正常
      【解决方案4】:

      如果这正是您需要解决的情况,您可以使用intval()strval()str_replace()substr()strlen() 来解决。

      $rel = '1.1.1.2'; // '1.1.1.2'
      
      // replace dots with empty strings
      $rel = str_replace('.', '', $rel); // '1112'
      // get the integer value
      $num = intval($rel); // 1112
      // add 1
      $num += 1; // 1113
      
      // convert it back to a string
      $str = strval($num); // '1113'
      // initialize the return value
      $ret = ''; 
      
      // for each letter in $str
      for ($i=0; $i<strlen($str); $i++) {
        echo "Current ret: $ret<br>";
        $ret .= $str[$i] . '.'; // append the current letter, then append a dot
      }
      $ret = substr($ret, 0, -1); // remove the last dot
      
      echo "Incremented value: " . $ret;
      

      但是,此方法会将 1.1.1.9 更改为 1.1.2.0。如果这就是你想要的,那就没问题了。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-03-06
        • 2012-06-13
        • 2015-12-09
        • 2014-11-18
        • 1970-01-01
        • 1970-01-01
        • 2011-05-18
        相关资源
        最近更新 更多