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?
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.
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.
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.
Use the addition (+) operator, e.g. Number('1') + Number('2') . The addition operator will return the sum of the numbers.
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:
(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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With