[interchange-bugs] [rt.icdevgroup.org #349] Vend::Util::round_to_frac_digits() simplification

Mark Overmeer via RT interchange at rt.icdevgroup.org
Mon Mar 26 13:05:59 UTC 2012


<URL: http://rt.icdevgroup.org/Ticket/Display.html?id=349 >

* Peter Ajamian via RT (interchange at rt.icdevgroup.org) [120321 21:33]:
> On 22/03/12 09:34, Mark Overmeer via RT wrote:
> >  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
> 
> Right, I even tried this by multiplying by 1.0000000001 (or something
> like that) to just nudge the value up a tiny bit and it worked (adding
> will have the problem that it won't work correctly for negative
> numbers).  The issue here, though, is that floats are unreliable for
> financial calculations and it's better to just avoid them than to try to
> overcome their problems with workarounds like this.

The argument is correct, the implementation inconsistent.  You
are using floating point and printf everywhere in the code.

Example of conversion into float:

 package Vend::Util;
 ...
 sub currency {
    my($amount, $noformat, $convert, $opt) = @_;
    ...
        $pd = $Vend::Cfg->{Locale_repository}{$opt->{locale}}{PriceDivide};
    ...
    if($pd and $convert) {
        $amount = $amount / $pd;          <--- even when $pd==1


Example of printf, to convert float to string

 package Vend::Util;
 ...
 sub round_to_frac_digits {
    my ($num, $digits) = @_;
    ...
    $num =~ /^(-?)(\d*)(?:\.(\d+))?$/     <--- when $num is float
        or return $num;

> So we're basically back to just fixing the current function for the
> problems you pointed out originally.

If you use floats everywhere already, then that's not really an argument
to have difficult and slow processing here. It may have been better to
store money in cents, in an object with "use integer" calculation.

Floats are your enemy, but you do not have too fear them.
-- 
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