Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Because floating point arithmetic != real number arithmetic. An illustration of the difference due to imprecision is, for some floats <code>a</code> and <code>b</code>, <code>(a+b)-b != a</code>. This applies to any language using floats. </p> <p>Since <a href="http://en.wikipedia.org/wiki/Floating_point" rel="noreferrer">floating point</a> are binary numbers with finite precision, there's a finite amount of <a href="http://en.wikipedia.org/wiki/Floating_point#Representable_numbers.2C_conversion_and_rounding" rel="noreferrer">representable numbers</a>, which leads <a href="http://en.wikipedia.org/wiki/Floating_point#Accuracy_problems" rel="noreferrer">accuracy problems</a> and surprises like this. Here's another interesting read: <a href="http://docs.sun.com/source/806-3568/ncg_goldberg.html" rel="noreferrer">What Every Computer Scientist Should Know About Floating-Point Arithmetic</a>. </p> <hr> <p>Back to your problem, basically there is no way to accurately represent 34.99 or 0.01 in binary (just like in decimal, 1/3 = 0.3333...), so approximations are used instead. To get around the problem, you can:</p> <ol> <li><p>Use <a href="http://php.net/manual/en/function.round.php" rel="noreferrer"><code>round($result, 2)</code></a> on the result to round it to 2 decimal places.</p></li> <li><p>Use integers. If that's currency, say US dollars, then store $35.00 as 3500 and $34.99 as 3499, then divide the result by 100.</p></li> </ol> <p>It's a pity that PHP doesn't have a decimal datatype like <a href="https://en.wikipedia.org/wiki/Decimal_data_type#Language_support" rel="noreferrer">other</a> <a href="http://docs.python.org/library/decimal.html" rel="noreferrer">languages</a> do.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload