convert a string to a number in JavaScript


Answers ( 1 )

    1. Using the Number function:

      • This is a straightforward way to convert a string to a number.
      • Example: let number = Number("123"); // number is 123
    2. Using the unary plus (+) operator:

      • Placing a + before a string converts it to a number.
      • Example: let number = +"123"; // number is 123
    3. Using parseInt or parseFloat:

      • parseInt converts a string to an integer, while parseFloat converts to a floating-point number.
      • Example: let intNumber = parseInt("123", 10); // intNumber is 123
      • Example: let floatNumber = parseFloat("123.45"); // floatNumber is 123.45
      • Note: The second argument in parseInt is the radix (base of the numerical system), typically 10 for decimal numbers.
    4. Using Math.floor, Math.ceil, or Math.round:

      • These can be used if you want to convert to an integer with specific rounding. First convert the string to a float, then apply the rounding method.
      • Example: let number = Math.floor(parseFloat("123.45")); // number is 123
    5. Using Number.parseInt and Number.parseFloat (ES6 and later):

      • These are more recent additions and work similarly to parseInt and parseFloat, but are methods on the Number object.
      • Example: let intNumber = Number.parseInt("123", 10); // intNumber is 123
      • Example: let floatNumber = Number.parseFloat("123.45"); // floatNumber is 123.45

    It's important to note that if the string cannot be converted to a number, these methods will return NaN (Not a Number). Additionally, when using parseInt or parseFloat, if the string starts with a number followed by non-numeric characters, it will parse up to the non-numeric characters. For instance, parseInt("123abc") will return 123.

Leave an answer