Pathologically Eclectic Rubbish Lister  
PerlMonks 
Why am I getting long decimals (eg, 19.9499999999999) instead of the numbers I should be getting (eg, 19.95)?by faq_monk (Initiate) 
on Oct 08, 1999 at 00:20 UTC ( #577=perlfaq nodetype: print w/replies, xml )  Need Help?? 
Current Perl documentation can be found at perldoc.perl.org. Here is our local, outdated (pre5.6) version: The infinite set that a mathematician thinks of as the real numbers can only be approximate on a computer, since the computer only has a finite number of bits to store an infinite number of, um, numbers. Internally, your computer represents floatingpoint numbers in binary. Floatingpoint numbers read in from a file or appearing as literals in your program are converted from their decimal floatingpoint representation (eg, 19.95) to the internal binary representation. However, 19.95 can't be precisely represented as a binary floatingpoint number, just like 1/3 can't be exactly represented as a decimal floatingpoint number. The computer's binary representation of 19.95, therefore, isn't exactly 19.95.
When a floatingpoint number gets printed, the binary floatingpoint representation is converted back to decimal. These decimal numbers are displayed in either the format you specify with
This affects all computer languages that represent decimal floatingpoint numbers in binary, not just Perl. Perl provides arbitraryprecision decimal numbers with the Math::BigFloat module (part of the standard Perl distribution), but mathematical operations are consequently slower. To get rid of the superfluous digits, just use a format (eg, printf("%.2f", 19.95)) to get the required precision. See Floatingpoint Arithmetic.

