How to convert a string representation of a number into a integer with javascript ?

Published: March 03, 2022

Updated: December 09, 2022

Tags: Javascript;

DMCA.com Protection Status

Examples of how to convert a string representation of a number into a integer with javascript :

Convert a string into an integer

Let's consider the following variable

var s = '42'

The variable type can be checked using typeof

console.log( typeof s );

gives here

string

To convert the above string into a integer, a solution is to use parseInt()

var i = parseInt(s)

console.log( i );

gives

42

and now if we check the type

console.log( typeof i );

it returns:

number

if s = '3.1415'

if the string is a represenation of a float

var s = '3.1415'
var i = parseInt(s)
console.log( i );

it gives

3

if s = '301 984 2472'

If the string contains number separated by spaces:

var s = '301 984 2472'
var i = parseInt(s)
console.log( i );

its returns the first number

301

if s = 'I am 42''

If the string starts with a letter:

var s = 'I am 42'
var i = parseInt(s)
console.log( i );

it gives

NaN

if s = '42 is the answer!''

However if the string starts with a number

var s = '42 is the answer!'
var i = parseInt(s)
console.log( i );

it gives

42

Comparing a string with a integer

Note:

var s = '42'
var i = parseInt(s)

console.log( i == s );

gives

true

while

console.log( i === s );

gives

false