PHP 错误逼近 printf [英] PHP wrong approximation with printf

查看:60
本文介绍了PHP 错误逼近 printf的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am fully aware of the floating point representation in binary format, so I know there are mathematical "impossibilities" when trying to perfectly represent a floating point number in any programming language. However, I would expect a programming language to follow some well known and well established rules when dealing with approximation.

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

Having said so, I read (here on stackoverflow too) that printf in PHP is probably the best way to "correctly truncate/approximate" a number, and - again - I am fully aware and I can easily code a one-line-function to give me the "perfect" approximation. This is just to avoid answers like "why don't you use XXX or do 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 1.51
1.509000 1.51

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 1.51
1.509000 1.51

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

As you can easily see, 1.504 is (correctly) printed as 1.50, and 1.506 is (correctly) printed as 1.51. But why 1.505 is printed as 1.50?! It MUST BE 1.51, not 1.50!

谢谢...

推荐答案

您应该使用 round 函数显式舍入值,以便您能够使用参数 mode,值为:

You should explicitly round the values using the round function, so that you are able to use the argument mode with values of:

PHP_ROUND_HALF_UP -- 将 val 向上舍入到远离零的精确小数位,当它到达一半时.将 1.5 变成 2,将 -1.5 变成 -2.

PHP_ROUND_HALF_DOWN -- 将 val 向下舍入到接近零的精确小数位,当它到达一半时.将 1.5 变为 1,将 -1.5 变为 -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));
}

这篇关于PHP 错误逼近 printf的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆