Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

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

2 Answers 2

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 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

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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