Is there a way to set 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
Is there a way to set 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
There is no way to globally change this
If it is just for display purposes then use sprintf("%.3f", $value);
For mathematical purposes (int(($value * 1000.0) + 0.5) / 1000.0)
. This would work for positive numbers. Would need to change it to work with negative numbers though.
How about 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
/I3az/