Why does it only count the first number? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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

23rd Feb 2019, 11:59 AM
Vincenzinho
Vincenzinho - avatar
5 Answers
+ 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!
23rd Feb 2019, 12:17 PM
Benneth Yankey
Benneth Yankey - avatar
+ 2
In addition to what Ben Bright said, you can directly typecast them. a= Number(prompt(....)) b= Number(prompt(...))
23rd Feb 2019, 12:20 PM
Шащи Ранжан
Шащи Ранжан - avatar
+ 1
It's bcz a and b are of string type and not Number. Convert them into numbers and it'll work.
23rd Feb 2019, 12:05 PM
Шащи Ранжан
Шащи Ранжан - avatar
+ 1
Thank you very much Ben Bright and Shashi Ranjan
23rd Feb 2019, 12:29 PM
Vincenzinho
Vincenzinho - avatar
0
How should i replace them in numbers, I Don't understanf
23rd Feb 2019, 12:09 PM
Vincenzinho
Vincenzinho - avatar