Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>1.2 + 1.1 may be ok but 0.2 + 0.1 may not be ok.</p> <p>This is a problem in virtually every language that is in use today. The problem is that 1/10 cannot be accurately represented as a binary fraction just like 1/3 cannot be represented as a decimal fraction.</p> <p>The workarounds include rounding to only the number of decimal places that you need and either work with strings, which are accurate:</p> <pre><code>(0.2 + 0.1).toFixed(4) === 0.3.toFixed(4) // true </code></pre> <p>or you can convert it to numbers after that:</p> <pre><code>+(0.2 + 0.1).toFixed(4) === 0.3 // true </code></pre> <p>or using Math.round:</p> <pre><code>Math.round(0.2 * X + 0.1 * X) / X === 0.3 // true </code></pre> <p>where <code>X</code> is some power of 10 e.g. 100 or 10000 - depending on what precision you need.</p> <p>Or you can use cents instead of dollars when counting money:</p> <pre><code>cents = 1499; // $14.99 </code></pre> <p>That way you only work with integers and you don't have to worry about decimal and binary fractions at all.</p> <h2>2017 Update</h2> <p>The situation of representing numbers in JavaScript may be a little bit more complicated than it used to. It <strong>used to be the case</strong> that we had only one numeric type in JavaScript:</p> <ul> <li>64-bit floating point (the <a href="https://en.wikipedia.org/wiki/IEEE_754-1985#Double-precision_64_bit" rel="nofollow noreferrer">IEEE 754 double precision floating-point number</a> - see: <a href="http://www.ecma-international.org/ecma-262/5.1/index.html#sec-8.5" rel="nofollow noreferrer">ECMA-262 Edition 5.1, Section 8.5</a> and <a href="http://www.ecma-international.org/ecma-262/6.0/index.html#sec-ecmascript-language-types-number-type" rel="nofollow noreferrer">ECMA-262 Edition 6.0, Section 6.1.6</a>)</li> </ul> <p><strong>This is no longer the case</strong> - not only there are currently more numerical types in JavaScript today, more are on the way, including a proposal to add arbitrary-precision integers to ECMAScript, and hopefully, arbitrary-precision decimals will follow - see this answer for details:</p> <ul> <li><a href="https://stackoverflow.com/questions/5179836/difference-between-floats-and-ints-in-javascript/5179886#5179886">Difference between floats and ints in Javascript?</a></li> </ul> <h2>See also</h2> <p>Another relevant answer with some examples of how to handle the calculations:</p> <ul> <li><a href="https://stackoverflow.com/questions/44949148/node-giving-strange-output-on-sum-of-particular-float-digits/44949594#44949594">Node giving strange output on sum of particular float digits</a></li> </ul>
 

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