为什么 Perl 的 sprintf 不能正确舍入浮点数? [英] Why does Perl's sprintf not round floating point numbers correctly?
问题描述
我正在寻找 Perl 的内置函数使用的舍入约定 sprintf.
I was out looking for the rounding convention used by Perl's built-in function sprintf.
我在想它会进行正常的舍入(例如 ROUND_HALF_UP,如 Java 的舍入模式约定),但进一步挖掘证明这是错误的:
I was thinking that it does a normal rounding (e.g. ROUND_HALF_UP as in Java's rounding mode convention), but digging further proved this to be wrong:
> /usr/local/bin/perl5.10.1 -e 'print(sprintf("%.2f", shift @ARGV)."
");' 0.335
0.34
> /usr/local/bin/perl5.10.1 -e 'print(sprintf("%.2f", shift @ARGV)."
");' 1.335
1.33
推荐答案
浮点数不是十进制小数的精确表示这一事实让您感到困惑.这是我得到的:
You have been bitten by the fact that floating point numbers are not exact representations of decimal fractions. Here's what I get:
DB<1> $a=0.335
DB<5> print sprintf("%.19f",$a)
0.3350000000000000200
DB<7> $b=1.335
DB<8> print sprintf("%.19f",$b)
1.3349999999999999645
DB<9>
由于 0.335 在内部表示为略大于 0.335,因此四舍五入为 0.34,而 1.335 略小于 1.335,因此四舍五入为 1.33.
Since 0.335 is represented internally as slightly larger than 0.335 it rounds to .34, while 1.335 is slightly LESS than 1.335, so it rounds to 1.33.
这篇关于为什么 Perl 的 sprintf 不能正确舍入浮点数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!