2.3. Rounding Floating-Point NumbersProblemYou 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 Recipe 2.2 ), as well as in situations where you must reduce the precision of your answers for readability. Solution
Use the Perl function $rounded = sprintf("%FORMATf", $unrounded); DiscussionRounding 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 $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 use POSIX; print "number\tint\tfloor\tceil\n"; @a = ( 3.3 , 3.5 , 3.7, -3.3 ); foreach (@a) { printf( "%.1f\t%.1f\t%.1f\t%.1f\n", $_, int($_), floor($_), ceil($_) ); } See Also
The Copyright © 2002 O'Reilly & Associates. All rights reserved. |
|