[interchange-bugs] [rt.icdevgroup.org #349] Vend::Util::round_to_frac_digits() simplification
Mark Overmeer via RT
interchange at rt.icdevgroup.org
Wed Mar 21 20:34:38 UTC 2012
<URL: http://rt.icdevgroup.org/Ticket/Display.html?id=349 >
* Peter Ajamian via RT (interchange at rt.icdevgroup.org) [120321 19:25]:
> peter at peter-desktop:~$ perl -le 'print sprintf "%.*f", 2, 0.125'
> 0.12
> peter at peter-desktop:~$ perl -le 'print sprintf "%.*f", 2, 0.1251'
> 0.13
>
> ... Definate rounding error there and there are other examples as well,
> and I wish the national debt was 12 cents.
It is not a rounding error in sprintf here, but in converting 0.125 into a
floating-point number. Probably it gets converted into 0.12499999999999
When you round that, you get 0.12 as shown.
So, you indicate a common problem with floats. Two solutions:
. always administer money as integer cents
. add 0.001 to sprintf (which I forgot in my original bug-report)
markov at moon> perl -le 'print sprintf "%.*f", 2, 0.125 +0.001'
0.13
markov at moon> perl -le 'print sprintf "%.*f", 2, 0.1251 + 0.0001'
0.13
The standard conversion routine from float to string in Perl does the
same thing.
--
Regards,
MarkOv
------------------------------------------------------------------------
Mark Overmeer MSc MARKOV Solutions
Mark at Overmeer.net solutions at overmeer.net
http://Mark.Overmeer.net http://solutions.overmeer.net
More information about the interchange-bugs
mailing list