0

What's wrong with my first program? I made an add script but someway it doesn't work

I tried to make an add function but it just treat the numbers like letters. ex: 1+1= 11 there's what I have made: var number1=prompt('please enter a number') var number2=prompt('please enter the number to add') alert(number1+number2)

25th Nov 2016, 8:23 AM
Losel Matos
Losel Matos - avatar
2 Answers
+ 3
prompt return a string not a number you have to use Number() function. like number1 = Number(number1); var number1=prompt('please enter a number') var number2=prompt('please enter the number to add') number1 = Number(number1); number2 = Number(number2); alert(number1+number2); You can also use alert(eval(number1+'+'+number2));
25th Nov 2016, 8:33 AM
Aditya kumar pandey
Aditya kumar pandey - avatar
+ 3
u will have to convert those to numbers first and then add them using parseInt() funⁿ. The parseInt() function parses a string and returns an integer. parseInt(num); // default way (no radix) parseInt(num, 10); // parseInt with radix (decimal) eg: var a = parseInt("10") + "<br>"; The radix parameter is used to specify which numeral system to be used, for example, a radix of 16 (hexadecimal) indicates that the number in the string should be parsed from a hexadecimal number to a decimal number. If the radix parameter is omitted, JavaScript assumes the following: If the string begins with "0x", the radix is 16 (hexadecimal)If the string begins with "0", the radix is 8 (octal). This feature is deprecatedIf the string begins with any other value, the radix is 10 (decimal) Note: Only the first number in the string is returned! Note: Leading and trailing spaces are allowed. Note: If the first character cannot be converted to a number, parseInt() returns NaN.
25th Nov 2016, 8:34 AM
Madhuri Sh@h
Madhuri Sh@h - avatar