温馨提示:本文翻译自stackoverflow.com,查看原文请点击:perl - How to round 4.44445 to 4.45?
perl rounding

perl - 如何将4.44445舍入为4.45?

发布于 2020-04-10 16:51:50

有人知道不是四舍五入而是四舍五入的模块吗?

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

sprintfMath::BigFloatMath::BigRat不能这样做=(

查看更多

提问者
Eugen Konkov
被浏览
110
choroba 2020-02-02 00:51

我仍然不了解规则的工作原理,但是bfroundMath :: BigFloat进行操作可能会返回您想要的结果。

#!/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;