EN
JavaScript - convert string to integer
3 points
In this article, we can find different ways how to parse integer numbers with parseInt
function in JavaScript.
This section shows how to convert with built-in parseInt
method some text to an integer.
xxxxxxxxxx
1
var text = '123';
2
var number = parseInt(text);
3
4
console.log(number === 123); // true
Using the parseInt()
method we can also parse floating point number and it will be rounded to an integer, look at the below example.
xxxxxxxxxx
1
var text = '123.12';
2
var number = parseInt(text);
3
4
console.log(text);
5
console.log(number);
6
console.log(number === 123); // true
parseInt
method during conversion ignores all characters that are not digits and occur after the number. It makes it possible to parse numbers with units.
xxxxxxxxxx
1
var number = parseInt('1px'); // pixels (px)
2
console.log(number === 1); // true
3
4
var number = parseInt('2cm'); // centimeters (cm)
5
console.log(number === 2); // true
6
7
var number = parseInt('3in'); // inches (in)
8
console.log(number === 3); // true
9
10
var number = parseInt('4%'); // percentages (%)
11
console.log(number === 4); // true