# [ACCEPTED]-How do I set the floating point precision in Perl?-floating-accuracy

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 1 cases:

```
say $x; # => 1.124
say $y; # => 3.333
say $x + $y; # => 4.457
```

There is no way to globally change this.

If 5 it is just for display purposes then use 4 `sprintf("%.3f", $value);`

.

For mathematical purposes, use `(int(($value * 1000.0) + 0.5) / 1000.0)`

. This 3 would work for positive numbers. You would 2 need to change it to work with negative 1 numbers though.

I wouldn't recommend to use sprintf("%.3f", $value).

Please 2 look at the following example: (6.02*1.25 1 = 7.525)

`printf("%.2f", 6.02 * 1.25) = 7.52`

`printf("%.2f", 7.525) = 7.53`

Treat the result as a string and use `substr`

. Like 3 this:

```
$result = substr($result,0,3);
```

If you want to do rounding, do it as 2 string too. Just get the next character 1 and decide.

Or you could use the following to truncate 2 whatever comes after the third digit after 1 the decimal point:

```
if ($val =~ m/([-]?[\d]*\.[\d]{3})/) {
$val = $1;
}
```

More Related questions

We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.