javascript tutorial - [Solved-5 Solutions] Convert a string into an integer - javascript - java script - javascript array



Problem:

How do I convert a string into an integer in JavaScript?

Solution 1:

The simplest way would be to use the native Number function:

var x = Number("1000")
click below button to copy the code. By JavaScript tutorial team

If that doesn't work for you, then there are the parseInt, unary plus, parseFloat with floor, and Math.round methods.

Solution 2:

parseInt function:

var number = parseInt("10");
click below button to copy the code. By JavaScript tutorial team

But there is a problem. If you try to convert "010" using parseInt function, it detects as octal number, and will return number 8. So, you need to specify a radix (from 2 to 36). In this case base 10.

parseInt(string, radix)
click below button to copy the code. By JavaScript tutorial team

Example:

var result = parseInt("010", 10) == 10; // Returns true

var result = parseInt("010") == 10; // Returns false

click below button to copy the code. By JavaScript tutorial team

Solution 3:

var rounded = Math.floor(Number("97.654"));  // other options are Math.ceil, Math.round
var fixed = Number("97.654").toFixed(0); // rounded rather than truncated
var bitwised = Number("97.654")|0;  // do not use for large numbers

click below button to copy the code. By JavaScript tutorial team

Solution 4:

ParseInt() and + are different

parseInt("10.3456") // returns 10

+"10.3456" // returns 10.3456

click below button to copy the code. By JavaScript tutorial team

Solution 5:

Try parseInt.

var number = parseInt("10", 10); //number will have value of 10.
click below button to copy the code. By JavaScript tutorial team

Related Searches to javascript tutorial - Convert a string into an integer