0

Javascripts numeric type is extremely unpredictable with regards to significant figures and sometimes rounding. This JSFiddle includes a good example of the problem where the value 0 can never be reliably reached in a series of addition and subtraction operations (and other suspect results are also visible).

What rules can I follow to reliably produce correct floating point arithmetic results in javascript?

For reference, the JSFiddle content is contained below.

<input id="input" type="number" value="0" />
<button id="plus" type="button">+</button>
<button id="minus" type="button">-</button>

function modify(direction) {
    var modifier = direction * 0.10;
    var next = Number($('#input').val()) + modifier;
    $('#input').val(next);
}

$('#plus').on('click', function () {
    modify(1);
});

$('#minus').on('click', function () {
    modify(-1);
});
Laurentiu L.
  • 6,566
  • 1
  • 34
  • 60
Eric Rini
  • 1,830
  • 15
  • 20
  • That's a problem with floating point arithmetic in general. not Just JS. – litelite Aug 21 '15 at 20:01
  • You may be interested in [Precise Financial Calculation in JavaScript. What Are the Gotchas?](http://stackoverflow.com/questions/2876536/precise-financial-calculation-in-javascript-what-are-the-gotchas) and [What Every Computer Scientist Should Know About Floating-Point Arithmetic](http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html). – Andrew Morton Aug 21 '15 at 20:07
  • Possible duplicate of: http://stackoverflow.com/questions/1458633/how-to-deal-with-floating-point-number-precision-in-javascript – cybersam Aug 21 '15 at 20:08

0 Answers0