How to convert string into number in Javascript

By FoxLearn 11/26/2024 8:17:01 AM   69
In JavaScript, there are several ways to convert a string into a number.

The simplest way is to use the native Number() function for converting a string to a number in JavaScript.

For example, Using Number() to convert a string to an integer in JavaScript

let str = "123";
let num = Number(str); // Output 123

The Number() function converts a string to a number.

If that doesn't work, alternatives include parseInt, the unary plus (+), parseFloat with Math.floor, or Math.round methods.

For example, Using the Unary + Operator to convert string into number in Javascript

let str = "123";
let num = +str; // Output: 123

The unary + operator is a shorthand to convert a string to a number.

For example, Using parseInt() to convert a string to an integer

let str = "123";
let num = parseInt(str, 10); // The second argument is the radix (base), usually 10.

If the string represents an integer, you can use parseInt()

For example, Using parseFloat() to convert a string to a float

let str = "123.45";
let num = parseFloat(str); // Output: 123.45

If the string represents a decimal or floating-point number, use parseFloat()

In some contexts, JavaScript automatically converts strings to numbers.

For example:

let str = "123";
let num = str * 1; // Implicit conversion using arithmetic operation

For example, Using Math.floor()

let str = "123.45";
let num = Math.floor(Number(str)); // floor() automatically converts string to number

Interestingly, Math.round (like Math.floor) can convert a string to a number, making it a great option if rounding is needed or the string contains an integer.

var round = Math.round;
var x = round("1000"); // Equivalent to round("1000", 0)

If the string cannot be converted to a valid number, most methods return NaN

You can check for this using isNaN()

For example:

let invalidStr = "xyz";
let num = Number(invalidStr);
console.log(isNaN(num)); // Output: true

Always ensure the input string is properly formatted to avoid unexpected results.