Perl Language Reference Manualby Larry Wall and others Paperback (6"x9"), 724 pages ISBN 9781906966027 RRP £29.95 ($39.95) Sales of this book support The Perl Foundation! Get a printed copy>>> |

## 7.38 Floating-point Arithmetic

While `use integer`

provides integer-only arithmetic, there is no
analogous mechanism to provide automatic rounding or truncation to a
certain number of decimal places. For rounding to a certain number
of digits, sprintf() or printf() is usually the easiest route.
See "Data Manipulation" (perlfaq4) in the *Perl FAQ*.

Floating-point numbers are only approximations to what a mathematician would call real numbers. There are infinitely more reals than floats, so some corners must be cut. For example:

printf "%.20g\n", 123456789123456789; # produces 123456789123456784

Testing for exact floating-point equality or inequality is not a good idea. Here's a (relatively expensive) work-around to compare whether two floating-point numbers are equal to a particular number of decimal places. See Knuth, volume II, for a more robust treatment of this topic.

sub fp_equal { my ($X, $Y, $POINTS) = @_; my ($tX, $tY); $tX = sprintf("%.${POINTS}g", $X); $tY = sprintf("%.${POINTS}g", $Y); return $tX eq $tY; }

The POSIX module (part of the standard perl distribution) implements ceil(), floor(), and other mathematical and trigonometric functions. The Math::Complex module (part of the standard perl distribution) defines mathematical functions that work on both the reals and the imaginary numbers. Math::Complex not as efficient as POSIX, but POSIX can't work with complex numbers.

Rounding in financial applications can have serious implications, and the rounding method used should be specified precisely. In these cases, it probably pays not to trust whichever system rounding is being used by Perl, but to instead implement the rounding function you need yourself.

ISBN 9781906966027 | Perl Language Reference Manual | See the print edition |