5

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?

7

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.

  • 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. – Nicole Dec 23 '10 at 5:29
  • parseInt("09") returns 9 in my Firebug. – Victor Piousbox Apr 9 '14 at 21:34
4

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

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