How do I set the floating point precision in Perl?

烈酒焚心 提交于 2019-11-29 09:18:05
Xetius

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.

draegtun

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

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

Peiti Li

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.

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