let userInput = prompt('Enter an integer');
console.log(Number(userInput));
I entered ’10’ and it is logging out NaN.
I thought Number() converted a string to a number value.
let userInput = prompt('Enter an integer');
console.log(Number(userInput));
I entered ’10’ and it is logging out NaN.
I thought Number() converted a string to a number value.
2
Answers
To extract a number from a string you need to use
Number.parseInt(variable)
orNumber.parseFloat(variable)
.Using
Number(variable)
just ensures that the result will be a numeric value. AndNaN
, though not a number, is still numeric.If the string only contains an unformatted number it will return the number. But if the string contains a formatted number or any other non numerical character, then
Number(variable)
will result itNaN
.Probably the result of your prompt contains a non numerical character.
Try running the snippet below with the numbers
55.555,55
and55,555.55
:NOTE:
parseInt
andparseFloat
can still returnNaN
if the variable content is not a numeric string that fullfils the internal lexical grammar.https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#numeric_literals
It could be due to some hidden characters like whitespace in your input string. Number() does the conversion of a string to a number; it fails if the string contains anything that cannot be directly interpreted as part of a number-that is, things like spaces or non-numeric characters. You typed ’10’, but leading or trailing spaces may be causing function Number() to return NaN.
You can eliminate that by doing a little trim() method that takes off any extra spaces around the input.
The code above works fine.