I have two strings which contain only numbers:
var num1 = '20',
num2 = '30.5';
I would have expected that I could add them together, but they are being concatenated instead:
num1 + num2; // = '2030.5'
How can I force these strings to be treated as numbers?
MDN docs for parseInt
MDN docs for parseFloat
In parseInt radix is specified as ten so that we are in base 10. In nonstrict javascript a number prepended with
0
is treated as octal. This would obviously cause problems!Also see ChaosPandion's answer for a useful shortcut using a unary operator. I have set up a fiddle to show the different behaviors.
http://jsfiddle.net/EtX6G/
Try this if you are looking for simple Javascript code and want to use two input box and add numbers from the two value. Here's the code.
for more details please visit http://informativejavascript.blogspot.nl/2012/12/javascript-basics.html
You may use like this:
When apply *1 in num1, convert string a number.
if num1 contains a letter or a comma, returns NaN multiplying by 1
if num1 is null, num1 returns 0
kind regards!!!
Make sure that you round your final answer to less than 16 decimal places for floats as java script is buggy.
For example 5 - 7.6 = -2.5999999999999996
Use the
parseFloat
method to parse the strings into floating point numbers: