PHP sprintf 输出 2 位小数

PHP sprintf output 2 decimals

我在 php 中编写一些代码,我发现了这个问题:

$a = 4.60;
$b = 5.05; 
$c = 2.60;

$r = ($a + $b + $c) * 0.1;

echo "r: $r\n";
echo "r sprintf1: " . sprintf("%.2f",$r) . "\n";
echo "r sprintf2: " . sprintf("%.2f",1.225) . "\n";

输出为:

r: 1.225
r sprintf1: 1.22
r sprintf2: 1.23

如您所见,当结果应该相同时,sprintf 的行为有所不同。这是为什么?

谢谢!

当您计算浮点数 ($r = ($a + $b + $c) * 0.1;) 时,它的结果不完全是 1.225,而是类似于 1.22499999999999986677323704498。这就是它发生的原因。

So never trust floating number results to the last digit, and do not compare floating point numbers directly for equality.

您可以从此处阅读官方文档中的更多详细信息Floating point precision

因为浮点值不精确,用它们做数学运算只会加剧不精确性。

$a = 4.60;
$b = 5.05; 
$c = 2.60;

$r = ($a + $b + $c) * 0.1;

// greatly increase the floating point display precision
ini_set('precision', 30);

var_dump( $a, $b, $c, $r, 1.225 );

输出:

float(4.59999999999999964472863211995)
float(5.04999999999999982236431605997)
float(2.60000000000000008881784197001)
float(1.22499999999999986677323704498)
float(1.22500000000000008881784197001)

这就是为什么你应该永远不要使用浮点数来表示金钱。

http://moneyphp.org/