Igor
Igor

Reputation: 27268

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?

Something similar to TCL's:

global tcl_precision
set tcl_precision 3

Upvotes: 17

Views: 32226

Answers (5)

draegtun
draegtun

Reputation: 22570

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

Upvotes: 23

P Li
P Li

Reputation: 5242

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.

Upvotes: 1

Xetius
Xetius

Reputation: 46904

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.

Upvotes: 17

Soroush
Soroush

Reputation: 1

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;  
}

Upvotes: 0

Dmytro
Dmytro

Reputation: 191

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

Upvotes: 3

Related Questions