in reply to Fixed precision numbers

You can use sprintf('%.2f', $foo) to round it. There's probably a module does this automatically, but creating one isn't hard. Just tie a variable.

{ package BlahBlah; use Tie::Scalar; @ISA = 'Tie::StdScalar'; sub STORE { ${+shift} = sprintf '%0.2f', pop } } tie my $foo, 'BlahBlah'; $foo = 1; print "$foo\n"; # 1.00 $foo = 1.005; print "$foo\n"; # 1.00 $foo = 1.025; print "$foo\n"; # 1.02 $foo = 0; print "$foo\n"; # 0.00

Juerd
- http://juerd.nl/
- spamcollector_perlmonks@juerd.nl (do not use).

Replies are listed 'Best First'.
Re: Re: Fixed precision numbers
by dash2 (Hermit) on Feb 25, 2003 at 22:10 UTC
    It's not that simple. sprintf rounds mathematically (rounding .5 up or down, depending on... I think whether the integer portion is odd or even).

    for (0.35,0.45){print sprintf("%.1f",$_);print "\n"} # result: 0.3 0.5

    That won't work for accounting: you always need to round up.

    Dave

      That won't work for accounting: you always need to round up.

      No, it won't work for maths, but it *will* work for accounting. I think it was merlyn who told me sprintf's rounding was called "Banker's rounding" and showed me why it was important. Google has a lot of information about this phenomenon. In short: halves are rounded towards the nearest even integer, and that solves a lot of problems.

      I don't know about international accounting differences, but I don't think biasing rounding up is a good thing to do.

      Juerd
      - http://juerd.nl/
      - spamcollector_perlmonks@juerd.nl (do not use).
      

        Sounds like we need someone with accounting knowledge to deliver wisdom.... Interesting, anyway.

        dave hj~