+ 2

parseInt in this js programme

//code to reverse a number in js var a = prompt("Enter a value"); var b, sum = 0; var z = a; while(a > 0) { b = a % 10; sum = sum * 10 + b; a = parseInt(a / 10); } alert(sum); what is the exact use of parseInt in the above programme ? Why we can not use a = a/10 instead of a = parseInt(a/10)?

14th Nov 2018, 5:14 PM
Sachin M
Sachin M - avatar
2 Answers
+ 2
Sachin M you need to convert a/10 into int again- so Math.floor() or parseInt() will do it. How you should make changes: a=Math.floor(parseInt(al/10) Schindlabua explained very well I thought prompt returns string like in python, but it doesn't. Still it would be better you convert to int, first don't rely on implicit conversion. second if someone enter float, you better convert to Int before starting
14th Nov 2018, 6:41 PM
Roneel
Roneel - avatar
+ 1
You are right, that does not belong there. It should be `a = parseInt(prompt(...))` at the top, and later `a = Math.floor(a/10)`. The code you posted works but it is very inefficient. You do need to round down though so `a/10` is not enough.
14th Nov 2018, 5:19 PM
Schindlabua
Schindlabua - avatar