Adding two numbers in JavaScript incorrectly

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

The code above outputs something like:

base: 15000, upfront: 36, both: 1500036

Why is it joining the two numbers instead of adding them up?

I eventually want to set the value of another field to this amount using this:

mainPanel.feesPanel.initialLoanAmount.setValue(Ext.util.Format.number((base + upfront), '$0,000.00'));

And when I try that, it turns the number into the millions instead of 15,036.00. Why?

6 Answers

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.

Related