How do I set the floating point precision in Perl?
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
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.