Perl rounding error again

后端 未结 5 998
野性不改
野性不改 2020-12-10 07:07

The example to show the problem:

  • having a number 105;
  • divide with 1000 (result 0.105)
  • rouded to 2 decimal places should be: 0.11
5条回答
  •  旧巷少年郎
    2020-12-10 07:37

    I'd add use bignum to your original code example.

    use 5.014;
    use warnings;
    use bignum;
    
    my $i = 105;                # Parsed as Math::BigInt
    my $r = $i / 1000;          # Overloaded division produces Math::BigFloat
    say $r->ffround(-2, +inf);  # Avoid using printf and the resulting downgrade to common float.
    

    This solves the error you made in your use Math::BigFloat example by parsing your numbers into objects imediately and not waiting for you to pass the results of a round off error into Math::BigFloat->new

提交回复
热议问题