# Common mistakes with javascript arithmetic [closed]

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?

-

## closed as too broad by MichaelT, gnat, IxrecNov 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.

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";
``````

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. – 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
``````
-