Skip to main content

JavaScript Convert String to Number

In this article, we’ll explore various methods to convert a string into int in javascript. We will create a sample example to convert string data into integer type data. The are different ways to convert string to int in JavaScript.

There are the following methods that can be used to convert a string into an integer –

  • parseInt()
  • unary plus
  • parseFloat()
  • Math.round()
  • Number()

Checkout Other tutorials:

Convert String Into Integer Using parseInt()

parseInt is the most popular method to convert strings into integers. The parseInt() takes two parameters, The first parameter is the string value, and the second one is the radix. The radix parameter is used to specify which numeral system to be used.

var x = parseInt("1000", 10);

Output: 1000

The parseInt method gets a number from a string and returns them. The string must start with a number if not then it will return NAN.
parseInt("hello 1000", 10) //NaN

JavaScript String to Integer Using Number()

The JavaScript Number() method also helps to convert a string into a number. The number() method takes one argument which is a number.

Number('1000') //return 10000
Number('1,000') //return NaN
Number('1000.00') //return 10

String to int Using Math.floor()

The math package has a floor method that converts a string into an integer. The floor() is a static method and returns the largest integer less than or equal to the specified number.

Math.floor( 65.95); //  65
Math.floor(-65.08); // -66 

String to int Using Math.round()

The math.round() is another method that converts a string value into an integer. The math.round() returns the value of a number rounded to the nearest integer.

Math.round(65.95); //  66
Math.round(65.48); // 65 

String to int Using Unary(+)

You can also use the unary(+) operator to convert a string into an integer. It’s the simplest and easiest for data manipulation. A unary operator works on one value. The JavaScript has unary plus (+), unary minus (-), prefix / postfix increments (++), prefix / postfix decrements (–) operator.

var x = +"100" // 10;

Conclusion:

Converting strings to integers is a common task in JavaScript. You can use any of the listed method to convert string to int using javascript. Whether you can use parseInt(), Number(), or the unary plus operator.

Leave a Reply

Your email address will not be published. Required fields are marked *