JavaScript - convert string to integer

3 points
Created by:

In this article, we can find different ways how to parse integer numbers with parseInt function in JavaScript.

Integer parsing example

This section shows how to convert with built-in parseInt method some text to an integer.

// ONLINE-RUNNER:browser;

var text = '123';
var number = parseInt(text);

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.

// ONLINE-RUNNER:browser;

var text = '123.12';
var number = parseInt(text);

console.log(number === 123); // true

Parsing numbers with unit examples

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.

// ONLINE-RUNNER:browser;

var number = parseInt('1px'); // pixels (px)
console.log(number === 1); // true

var number = parseInt('2cm'); // centimeters (cm)
console.log(number === 2); // true

var number = parseInt('3in'); // inches (in)
console.log(number === 3); // true

var number = parseInt('4%'); // percentages (%)
console.log(number === 4); // true

See also

  1. JavaScript - how to convert string to number?

Alternative titles

  1. How to parse integer in JavaScript?
  2. JavaScript - parseInt method example
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

JavaScript - string conversion

Native Advertising
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

â€ïžđŸ’» 🙂