Adding two numbers in JavaScript incorrectly

Simple example:

 1 +1 == 2
"1"+1 == "11"
"1"*1 + 1 == 2

Ways to turn a string into a number:

  • parseInt(str)
  • parseInt(str,10)
  • parseFloat(str)
  • +str
  • str*1
  • str-0
  • str<<0
  • Number(str)

And here are some of the consequences: Results of converting various strings using the above techniques
(source: phrogz.net)

Number(str) has the same behavior as str*1, but requires a function call.

I personally use *1 as it is short to type, but still stands out (unlike the unary +), and either gives me what the user typed or fails completely. I only use parseInt() when I know that there will be non-numeric content at the end to ignore, or when I need to parse a non-base-10 string.

You can test the performance of these in your browser at my example page.


This might happen because they are strings. Try parsing them:

Global.alert(
    "base: " + base + ", upfront: " + upfront + ", both: " + 
    (parseInt(base) + parseInt(upfront))
);

If those numbers are decimal you will need the parseFloat method instead.

Tags:

Javascript