[英]How do I set the floating point precision in Perl?
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?有没有办法设置 Perl 脚本的浮点精度(到 3 位),而不必专门为每个变量更改它?
Something similar to TCL's:类似于 TCL 的东西:
global tcl_precision
set tcl_precision 3
Use Math::BigFloat
or bignum
:使用
Math::BigFloat
或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:或者用
bignum
代替:
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
There is no way to globally change this.没有办法全局改变这一点。
If it is just for display purposes then use sprintf("%.3f", $value);
如果仅用于显示目的,则使用
sprintf("%.3f", $value);
. .
For mathematical purposes, use (int(($value * 1000.0) + 0.5) / 1000.0)
.出于数学目的,请使用
(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.
不过,您需要将其更改为使用负数。
I wouldn't recommend to use sprintf("%.3f", $value).我不建议使用 sprintf("%.3f", $value)。
Please look at the following example: (6.02*1.25 = 7.525)请看下面的例子:(6.02*1.25 = 7.525)
printf("%.2f", 6.02 * 1.25) = 7.52
printf("%.2f", 7.525) = 7.53
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.