You want to round a floating-point value to a certain number of decimal places. This problem arises as a result of the same inaccuracies in representation that make testing for equality difficult (see Section 2.2), as well as in situations where you must reduce the precision of your answers for readability.
Use the Perl function
printf if you’re just trying to produce
$rounded = sprintf("%FORMATf", $unrounded);
Rounding can seriously affect some algorithms, so the rounding method used should be specified precisely. In sensitive applications like financial computations and thermonuclear missiles, prudent programmers will implement their own rounding function instead of relying on the programming language’s built-in logic, or lack thereof.
Usually, though, we can just use
f format lets you specify a particular number of
decimal places to round its argument to. Perl looks at the following
digit, rounds up if it is 5 or greater, and rounds down otherwise.
$a = 0.255; $b = sprintf("%.2f", $a); print "Unrounded: $a\nRounded: $b\n"; printf "Unrounded: $a\nRounded: %.2f\n", $a;
Three functions that may be useful if you want to round a
floating-point value to an integral value are
int, built into Perl, returns the integral portion
of the floating-point number passed to it (
$_ if it was called without an ...