Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I've ran into several oddities using javascripts floating point arithmetic, but I can never recall them off the top of my head!

What are some common mistakes when using JavaScript to do math?

share|improve this question

closed as too broad by MichaelT, gnat, Ixrec Nov 19 '15 at 22:01

There are either too many possible answers, or good answers would be too long for this format. Please add details to narrow the answer set or to isolate an issue that can be answered in a few paragraphs.If this question can be reworded to fit the rules in the help center, please edit the question.

up vote 7 down vote accepted

The common problems with javascript arithmetic relate to the use of parseInt, or the lack of.

Not using radix when converting strings to integers:

parseInt("0137"); // 95!
parseInt("0137", 10); // 137

Not using parseInt at all with arithmetic:

var a = "2";
alert(a + 5); // 25
alert(a - 5): // -3!

Misunderstanding floating point arithmetic (applies to all languages, not just JS):

alert(23 * 1.40 == 32.2); // false, 23 * 1.40 is represented as 32.199999999
alert((23 * 1.40).toFixed(1) == 32.2); // true

Calculating currency with floating points may lead to rounding errors, currency values should be treated as integers (multiplied with 100) before processing.

share|improve this answer
Number() is a suitable replacement for parseInt(str, 10). Don't forget that parseInt("09") (as you might use if you are parsing a time string) actually throws an error. – NickC Dec 23 '10 at 5:29
parseInt("09") returns 9 in my Firebug. – Victor Piousbox Apr 9 '14 at 21:34

A common mistake (although with strings & integers, not floats) is forgetting that JavaScript doesn't have strong typing. So you can run into situations where:

var myVar = 7;       // 7
myVar += 5;          // 12

var myVar = "7";     // 7
myVar += 5;          // 75

var myVar = "cat";   // cat
myVar += 5;          // cat5

All of these are perfectly valid statements in JavaScript.

But it gets weirder, because while "7" and "cat" are both strings, not all strings are treated the same:

var myVar = 77;
parseInt(myVar);     // 77

var myVar = "77";
parseInt(myVar);     // 77

var myVar = "cat";
parseInt(myVar);     // NaN

var myVar = "77cat";
parseInt(myVar);     // 77

Not to mention that (as @Tatu wrote):

var myVar = "077";
parseInt(myVar);     // 63
share|improve this answer

Not the answer you're looking for? Browse other questions tagged or ask your own question.