+ 1
Why does it only count the first number?
I was just trying to see what i can do with JS, so i made a little code where you can input 2 numbers and it Will show you which one is the highest, but the code is only looking to the first number. For example if you put in 9 and 24, it Will say that 9 is bigger than 24. Why is this?? https://code.sololearn.com/WGSVn7jwTKVD/?ref=app
5 Respostas
+ 2
as Shashi Ranjan said the returned value of prompt is a string. So when the inputs are 9 and 24, they are actually returned by prompt as "9" and "24".
String are compared lexicographically, where by 9 is compared to 2 instead of 24.
So you need to implicitly convert the prompt values to Numbers before you compare.
so you could use "+" to convert the strings to numbers in your code as follows:
if (+a > +b) {
// info here
}
else if (+a == +b) {
// info here
}
else {
// info here
}
Hope it helps, happy coding!
+ 2
In addition to what Ben Bright said, you can directly typecast them.
a= Number(prompt(....))
b= Number(prompt(...))
+ 1
It's bcz a and b are of string type and not Number. Convert them into numbers and it'll work.
+ 1
Thank you very much Ben Bright and Shashi Ranjan
0
How should i replace them in numbers, I Don't understanf