2

我完全了解二进制格式的浮点表示,因此我知道在尝试用任何编程语言完美表示浮点数时存在数学“不可能”。但是,我希望编程语言在处理近似值时遵循一些众所周知且完善的规则。

话虽如此,我读到(这里也是在stackoverflow上)PHP中的printf可能是“正确截断/近似”数字的最佳方法,并且 - 再次 - 我完全意识到并且我可以轻松编写单行函数给我“完美”的近似值。这只是为了避免诸如“你为什么不使用 XXX 或做 YYY?”之类的回答。

尝试这个:

for($i=0; $i<10; $i++) {
  $k = 1.50 + $i/1000;
  printf("%f %.2f<br>", $k, $k);
}

这是输出:

1.500000 1.50
1.501000 1.50
1.502000 1.50
1.503000 1.50
1.504000 1.50
1.505000 1.50
1.506000 1.51
1.507000 1.51
1.508000 01.510
1.510 1.51

如您所见,1.504(正确)打印为 1.50,而 1.506(正确)打印为 1.51。但是为什么 1.505 打印为 1.50?!它必须是 1.51,而不是 1.50!

谢谢...

4

1 回答 1

0

您应该使用该round函数显式四舍五入值,以便您能够使用mode具有以下值的参数:

PHP_ROUND_HALF_UP -- Round val up to precision decimal places away from zero, when it is half way there. Making 1.5 into 2 and -1.5 into -2.

PHP_ROUND_HALF_DOWN -- Round val down to precision decimal places towards zero, when it is half way there. Making 1.5 into 1 and -1.5 into -1.

功能:

float round ( float $val [, int $precision = 0 [, int $mode = PHP_ROUND_HALF_UP ]] )

查看完整描述:

http://php.net/manual/en/function.round.php

编辑:

for($i=0; $i<10; $i++) {
  $k = 1.50 + $i/1000;
  printf("%f %f<br>", $k, round($k,2,PHP_ROUND_HALF_UP));
}
于 2013-03-30T11:24:50.290 回答