Как округлить 4.44445 до 4.45? - PullRequest
0 голосов
/ 01 февраля 2020

Кто-нибудь знает модуль, который округляет не двоичный файл, а следующий:

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

sprintf, Math::BigFloat, Math::BigRat не может этого сделать = (

Ответы [ 2 ]

4 голосов
/ 01 февраля 2020

Я до сих пор не понимаю, как работают правила, но игра с bfround из Math :: 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;
0 голосов
/ 02 февраля 2020

Одно из многих возможных решений (хотя это противоречит математическим правилам)

use strict;
use warnings;
use feature 'say';

while( <DATA> ) {
    next if /^$/;
    chomp;
    say "$_ -> " . round($_);
}

sub round {
    my $number = shift;

    my $integer  = int($number);
    my $reminder = $number - $integer;

    $reminder += $reminder < 0.444445 ? 0 : 0.001;

    $number = $integer + $reminder;

    $number = sprintf "%.2f", $number;

    return $number;
}

__DATA__
4.444435
4.444445
4.445444
4.443000

Вывод

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