develooper Front page | perl.beginners | Postings from April 2010

Perl rounding errors?

Thread Next
From:
Rob Coops
Date:
April 26, 2010 03:38
Subject:
Perl rounding errors?
Message ID:
y2m867476851004260338ke377b6fck2aa1b0d10949d4f@mail.gmail.com
Hi list,

I am just wondering if I sumbled upon an error in perl an error in my logic
or somehtign else see the below perl one liners

$ perl -e '$n = 0.945; $r = sprintf("%.2f", $n); print "$r\n";'
0.94

$ perl -e '$n = 0.9451; $r = sprintf("%.2f", $n); print "$r\n";'
0.95

$ perl -e '$n = 0.9450; $r = sprintf("%.2f", $n); print "$r\n";'
0.94

$ perl -e '$n = 0.94500; $r = sprintf("%.2f", $n); print "$r\n";'
0.94

$ perl -e '$n = 0.945001; $r = sprintf("%.2f", $n); print "$r\n";'
0.95

Now I expected perl to round the number: 0.945 to 0.95 and not to 0.94 like
it is doing. I have no idea why it is doing this but I sure don't like it.
The problem is I have to do some VAT calculations on thousands of invoices
and invoice elements. I found that in rare cases I'm of by 1 cent or even 3
cents if there are lots of elements. Going over the logic I ran into this
problem.

Cany anyone advise me how to deal with this as I need to find a way to round
correctly in all cases not just in cases where Perl decides it is a good
idea to do so. :-)

Regards,

Rob

Thread Next


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About