Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding two numbers in JavaScript incorrectly [duplicate]

Tags:

javascript

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?

like image 279
Scott Avatar asked Sep 03 '10 17:09

Scott


People also ask

Why are my numbers not adding in JavaScript?

When you say prompt() it returns a string by default, so 12+12 is added like a string. You must cast the value to a number type and you can either use Number(prompt()) or parseInt(prompt()). Strings see '+' as concatenating operator.

How can I add two numbers in JavaScript?

Example 2: Add Two Numbers Entered by the User const num1 = parseInt(prompt('Enter the first number ')); const num2 = parseInt(prompt('Enter the second number ')); Then, the sum of the numbers is computed. const sum = num1 + num2; Finally, the sum is displayed.

How do you sum digits in JavaScript?

To sum all the digits in a number: Use the split() method to split the string into an array of digits. Use the reduce() method to sum all the digits in the array.

How do I sum two strings in JavaScript?

Use the addition (+) operator, e.g. Number('1') + Number('2') . The addition operator will return the sum of the numbers.


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

like image 66
Phrogz Avatar answered Sep 29 '22 19:09

Phrogz