0
Sum bugs
Hi, I'm a beginner and I'm facing this problem in Javascript : even though I don't think that I am wrong somewhere I don't get the correct result: var_a=10; var_b=10; var_c=10; x = var_a + var_b + var_c; As a result I get 101010 instead of 30. Can someone please help me?
4 Réponses
+ 2
Well, prompt returns a string.
You can always check the type of a variable using the typeof operator.
You can convert a string to a number either by:
- The unary plus sign
- The Number() function
- The parseInt() function
I would recommend parseInt, there is room for error on the user's side (it scans for a number in a string). + and Number do the same thing: They will convert the number if it's a number; or else return NaN.
And, just saying; don't post the same question twice.
0
Hello, fellow sir.
I'm 100% sure the code you included is not the one you are having problems with.
Your problem is one of the variables is a string, but it doesn't seem like that. Didn't you mean to write:
var_a = "10";
...
Your code like this is correct.
0
Well, actually the variables are from an input from the user.
var var_a=prompt('Enter the value: ');
I check and nope, they are not strings.
0
Thank you very much sir, now it works very well