php function: number_format()


php function: number_format()

$result = number_format($x, 2, '.', ','); //Will do the following correctly
115255 = 115,225.00
115255.4 = 115,225.40
115255.40 = 115,225.40
115255.455 = 115,255.46

但是我需要当用户在小数点后输入超过 2 位数字时,不要只将它们切成 2 位小数并按原样使用它......

115255.455 = 115,255.455
115255.4557 = 115,255.4557

我可以做这样的事情吗?

if($x == number_format($x, 3)) //I will do it in while loop later, lets test 3 now
    $result = number_format($x, 3, '.', ',');
else $result = number_format($x, 2, '.', ',');

前面的 if 条件永远不起作用,否则只有效

一种非传统的方法:

$parts = explode(".", $x);
$integerPart = number_format($parts[0], 0, '', ',');
$result = $integerPart.".".$parts[1];