How do I set the floating point precision in Perl?

Igor Oks picture Igor Oks · Dec 3, 2009 · Viewed 27.3k times · Source

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

Answer

draegtun picture draegtun · Dec 3, 2009

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