Warm tip: This article is reproduced from stackoverflow.com, please click
perl rounding

How to round 4.44445 to 4.45?

发布于 2020-04-10 16:02:25

Does anybody know the module which rounds not binary but as next:

4.444435 -> 4.44
4.444445 -> 4.45
4.445444 -> 4.45
4.443000 -> 4.44

The sprintf, Math::BigFloat, Math::BigRat can not do that =(

Questioner
Eugen Konkov
Viewed
92
choroba 2020-02-02 00:51

I still don't understand how the rules work, but playing with bfround from Math::BigFloat might return what you want.

#!/usr/bin/perl
use warnings;
use feature qw{ say };

use Math::BigFloat;

sub myround {
    my $bi = 'Math::BigFloat'->new("$_[0]");
    for (my $l = length $bi; $l > 1; --$l) {
        $bi->bfround(-$l, '+inf');
    }
    $bi
}

use Test::More tests => 8;

is myround(4.444435), 4.44;
is myround(4.444445), 4.45;
is myround(4.445444), 4.45;
is myround(4.443000), 4.44;

is myround(3.554444), 3.55;
is myround(3.554445), 3.56;
is myround(3.544445), 3.55;
is myround(3.555550), 3.56;