浮点值,小数点后两位


float value with two decimal places

如果浮点值(而不是字符串)是零,PHP中有没有任何方法可以让它们有两个小数位?

示例:

$v = 1.50

使用(float)floatval($v)会将数字返回为1.5

我知道我可以使用number_format()来获得任意精度,但这会返回一个字符串,一旦我将其转换为浮点值,我就会遇到同样的问题。

简单的答案是你不能。变量(作为float)只包含基准,1.51.50是一样的,内部存储为浮点数。

只有在显式(使用number_format())或隐式(直接打印变量或在调试器中检查值)将值转换为字符串时,才能看到打印为1.51.50的值。当您想将值写为字符串时,应该使用number_format()

这可能会对您有所帮助:

示例:

$foo = "105";
echo number_format((float)$foo, 2, '.', '');  // Outputs -> 105.00

这是另一种方式:

$num = 1.2;
$dec = 2;
echo sprintf('%0.'.$dec.'f', round($num, $dec)); 

响应:

1.20