<?xml version="1.0" encoding="windows-1252"?>
<node id="577" title="Why am I getting long decimals (eg, 19.9499999999999) instead of the numbers I should be getting (eg, 19.95)?" created="1999-10-07 20:20:52" updated="2005-08-15 12:29:15">
<type id="834">
perlfaq nodetype</type>
<author id="519">
faq_monk</author>
<data>
<field name="doctext">
&lt;P&gt;
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.

&lt;P&gt;
Internally, your computer represents floating-point numbers in binary.
Floating-point numbers read in from a file or appearing as literals in your
program are converted from their decimal floating-point representation (eg,
19.95) to the internal binary representation.

&lt;P&gt;
However, 19.95 can't be precisely represented as a binary floating-point
number, just like 1/3 can't be exactly represented as a decimal
floating-point number. The computer's binary representation of 19.95,
therefore, isn't exactly 19.95.

&lt;P&gt;
When a floating-point number gets printed, the binary floating-point representation is converted back to decimal. These decimal numbers are displayed in either the format you specify with 
&lt;CODE&gt;printf(),&lt;/CODE&gt; or the current output format for numbers (see
 [perlman:perlvar|$#] if you use print.  &lt;CODE&gt;$#&lt;/CODE&gt; has a different default value in Perl5 than it did in Perl4. Changing &lt;CODE&gt;$#&lt;/CODE&gt; yourself is deprecated.

&lt;P&gt;
This affects &lt;STRONG&gt;all&lt;/STRONG&gt; computer languages that represent decimal floating-point numbers in binary,
not just Perl. Perl provides arbitrary-precision decimal numbers with the
Math::BigFloat module (part of the standard Perl distribution), but
mathematical operations are consequently slower.

&lt;P&gt;
To get rid of the superfluous digits, just use a format (eg,
&lt;U&gt;printf(&amp;quot;%.2f&amp;quot;, 19.95)&lt;/U&gt;) to get the required precision. See [perlman:perlop|Floating-point Arithmetic].

&lt;P&gt;
</field>
</data>
</node>
