How do I set the floating point precision in Perl?

前端 未结 5 1945
失恋的感觉
失恋的感觉 2020-12-18 20:54

Is there a way to set a Perl script\'s floating point precision (to 3 digits), without having to change it specifically for every variable?

Something similar to TCL\

相关标签:
5条回答
  • 2020-12-18 21:20

    Or you could use the following to truncate whatever comes after the third digit after the decimal point:

    if ($val =~ m/([-]?[\d]*\.[\d]{3})/) {
        $val = $1;  
    }
    
    0 讨论(0)
  • 2020-12-18 21:29

    Treat the result as a string and use substr. Like this:

    $result = substr($result,0,3);
    

    If you want to do rounding, do it as string too. Just get the next character and decide.

    0 讨论(0)
  • 2020-12-18 21:33

    I wouldn't recommend to use sprintf("%.3f", $value).

    Please look at the following example: (6.02*1.25 = 7.525)

    printf("%.2f", 6.02 * 1.25) = 7.52

    printf("%.2f", 7.525) = 7.53

    0 讨论(0)
  • 2020-12-18 21:41

    There is no way to globally change this.

    If it is just for display purposes then use sprintf("%.3f", $value);.

    For mathematical purposes, use (int(($value * 1000.0) + 0.5) / 1000.0). This would work for positive numbers. You would need to change it to work with negative numbers though.

    0 讨论(0)
  • 2020-12-18 21:41

    Use Math::BigFloat or bignum:

    use Math::BigFloat;
    Math::BigFloat->precision(-3);
    
    my $x = Math::BigFloat->new(1.123566);
    my $y = Math::BigFloat->new(3.333333);
    

    Or with bignum instead do:

    use bignum ( p => -3 );
    my $x = 1.123566;
    my $y = 3.333333;
    

    Then in both cases:

    say $x;       # => 1.124
    say $y;       # => 3.333
    say $x + $y;  # => 4.457
    
    0 讨论(0)
提交回复
热议问题