3
$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?

Unknown.Vagrant
  • 252
  • 2
  • 12
  • 1
    Instead of exactly `13.485`, `$a` will likely contain `13.4849999999999994315658113919198513031005859375`, or `1101.0111110000101000111101011100001010001111010111` in base 2 (assuming double-precision IEEE754 numbers). So `13.48` is closer than `13.49`. – chtz Dec 29 '20 at 20:03

2 Answers2

2

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.

ikegami
  • 367,544
  • 15
  • 269
  • 518
0
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.

Dodger
  • 142
  • 2
  • 10