Rounding floating equal to 5

Viewed 83
$a = 13.485;
$b = 13.255;
printf '%.2f -- %.2f', $a, $b;

13.48 -- 13.26

but i need

13.49 -- 13.26

What is best way always round 5 to up?

2 Answers

485/1000 is a periodic number in binary (just like 1/3 in decimal).

                ____________________
485/1000 = 0.01111100001010001111010

As such, it can't accurately be represented as a floating point number. (It would require infinite storage.) The number you actually have is a little less than 13.485.

$ perl -E'say sprintf "%.100g", 13.485'
13.4849999999999994315658113919198513031005859375

Since 13.4849... is closer to 13.48 than to 13.49, it rounds to 13.48.


Conversely, the number you have instead of 13.255 is slightly larger than 13.255.

$ perl -E'say sprintf "%.100g", 13.255'
13.2550000000000007815970093361102044582366943359375

So this happens to produce 13.26 as desired.


If this matters to you, maybe you shouldn't be using floating point numbers.

use Math::Round 'round';

my $number = 13.485;
my $rounded = round($scalar * 100) / 100;
# rounded == 13.49

Caveat: this method only rounds .5 half of the time. That is, it rounds positive numbers up. Math::Round::round() rounds -3.5 to -4, which is down, not up. However, this may be what you mean.

Related