rounding numerical values: how to achieve “round half away from zero” with printf?

To be more precise: I actually mean “considering a given precision” of real numbers.

In Germany (in a financial context at least) “round half away from zero” is being used. …

Look at this – can you explain it?:

$ perl -e '$h = 3272.505; printf "%.2f --- %.10fn",$h,$h;'
3272.51 --- 3272.5050000000
$ perl -e '$h = 622.775; printf "%.2f --- %.10fn",$h,$h;'
622.77 --- 622.7750000000

I think we don’t see, what the real numbers really are. 3272.505 is supposedly kept as something like 3272.50499999 (<) as supposed to 622.775, which is supposedly kept closer (>=) to what we see. Apparently the results are acceptable outside the financial world, but within the financial world they are totally unacceptable. I have no idea, why the Perl community has been allowing this for such a long time.

Update 2015-11-21:

I fiddled on a subroutine, that essentially takes parameters like this:

sprintf("%7.2f",3272.505);

For the time being I call it like this:

&round_real_number__half_away_from_zero(
  'v' => 3272.505,
  'total_length' => 7,
  'post_decimal_points_digits' => 2);

In a way I am quite disappointed, that sprintf does not do, what I expect it to do.

This site uses Akismet to reduce spam. Learn how your comment data is processed.