如何在PHP中将字符串编号转换为字符串时防止x.0变为x

时间:2017-05-10 08:05:52

标签: php

for ( $d = 1.0 ; $d < 10000; $d = $d + 0.1 ) {
  $file = "...(LCCallNum:({$d}))";
  var_dump($file);
}

我需要$ d来保持1.0,2.0,3.0,4.0。但是当我变量插值时,它继续保持1,2,3,4,并转储$ file。如何防止它变成整数?

2 个答案:

答案 0 :(得分:2)

您可以使用number_format来解决此问题

<?php
    for ( $d = 1.0 ; $d < 2; $d += 0.1 ) {
      echo number_format($d,1)."\n";
    }
?>

现场演示:https://eval.in/791122

答案 1 :(得分:2)

使用sprintf(),如下所示:

for ($d = 1.0 ; $d < 10000; $d = $d + 0.1) {
    $file = sprintf("...(LCCallNum:(%.1F))", $d); 
    var_dump($file);
}

哪个输出:

string(20) "...(LCCallNum:(1.0))"
string(20) "...(LCCallNum:(1.1))"
string(20) "...(LCCallNum:(1.2))"
string(20) "...(LCCallNum:(1.3))"
string(20) "...(LCCallNum:(1.4))"
...