skip to Main Content
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


  1. To extract a number from a string you need to use Number.parseInt(variable) or Number.parseFloat(variable).

    Using Number(variable) just ensures that the result will be a numeric value. And NaN, 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 it NaN.

    Probably the result of your prompt contains a non numerical character.

    Try running the snippet below with the numbers 55.555,55 and 55,555.55:

    const myNumber = prompt('Enter a number.');
    
    console.log('myNumber =', myNumber);
    console.log('Number(myNumber) =', Number(myNumber));
    console.log('Number.parseInt(myNumber) =', Number.parseInt(myNumber));
    console.log('Number.parseFloat(myNumber) =', Number.parseFloat(myNumber));

    NOTE: parseInt and parseFloat can still return NaN 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

    Login or Signup to reply.
  2. 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.

    let userInput = prompt('Enter an integer');
    console.log(Number(userInput.trim()));

    The code above works fine.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search