代码之家  ›  专栏  ›  技术社区  ›  Igor

如何在Perl中设置浮点精度?

  •  14
  • Igor  · 技术社区  · 15 年前

    有没有一种方法可以设置Perl脚本的浮点精度(为3位),而不必专门针对每个变量进行更改?

    类似于TCL的产品:

    global tcl_precision
    set tcl_precision 3
    
    5 回复  |  直到 7 年前
        1
  •  21
  •   smonff David Verdin    4 年前

    使用 Math::BigFloat bignum :

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

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

    然后在这两种情况下:

    say $x;       # => 1.124
    say $y;       # => 3.333
    say $x + $y;  # => 4.457
    
        2
  •  16
  •   Peter Mortensen Abd Al-Kareem Attiya    7 年前

    没有办法在全球范围内改变这一点。

    sprintf("%.3f", $value); .

    出于数学目的,使用 (int(($value * 1000.0) + 0.5) / 1000.0) . 这将适用于正数。不过,您需要将其更改为使用负数。

        3
  •  3
  •   Dmytro    13 年前

    (6.02*1.25 = 7.525)

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

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

        4
  •  1
  •   Peter Mortensen Abd Al-Kareem Attiya    7 年前

    将结果视为字符串并使用 substr . 这样地:

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

    如果你想做四舍五入,也要像字符串一样做。只要找到下一个角色,然后决定。

        5
  •  0
  •   Soroush    12 年前

    或者,您可以使用以下方法截断小数点后第三位数字后面的内容:

    if ($val =~ m/([-]?[\d]*\.[\d]{3})/) {
        $val = $1;  
    }