How do I set the floating point precision in Perl?

一个人想着一个人 提交于 2019-11-28 02:40:44

问题


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's:

global tcl_precision
set tcl_precision 3

回答1:


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.




回答2:


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



回答3:


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




回答4:


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.




回答5:


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;  
}


来源:https://stackoverflow.com/questions/1838808/how-do-i-set-the-floating-point-precision-in-perl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!