2009-10-30 111 views
5

我一直在尋找Perl內置函數sprintf使用的舍入約定。爲什麼Perl的sprintf不能正確地舍入浮點數?

我想,它正常的四捨五入(如ROUND_HALF_UP在Java's rounding mode convention),但挖進一步證明這是錯誤的:

> /usr/local/bin/perl5.10.1 -e 'print(sprintf("%.2f", shift @ARGV)."\n");' 0.335 
0.34 
> /usr/local/bin/perl5.10.1 -e 'print(sprintf("%.2f", shift @ARGV)."\n");' 1.335 
1.33 
+7

print(sprintf(...))?我不知道是否有一個「printf」... – jrockway 2009-10-31 05:31:37

+1

看看[Perl Cookbook recipe 2.2 - 舍入浮點數](http://books.google.com/books?id=hP4IRp8xwTkC&pg=PA64&lpg=PA64&dq=圓整+數字+ perl + cookbook&source = bl&ots = ti7Tyxr3s7&sig = gyWX-iySyiVZef0vB43ZuIakkuw&hl = en&ei = RPzrStmzO4z0MarIvKkI&sa = X&oi = book_result&ct = result&resnum = 1&ved = 0CAwQ6AEwAA#v = onepage&q =&f = false) – heferav 2009-10-31 09:12:55

回答

16

您已被事實浮點數不是被咬小數部分的精確表示。下面是我得到:

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。

相關問題