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

Active March 03, 2022    /    Viewed 64    /    Comments 0    /    Edit


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

References


Card image cap
profile-image
Daidalos

Hi, I am Ben.

I have developed this web site from scratch with Django to share with everyone my notes. If you have any ideas or suggestions to improve the site, let me know ! (you can contact me using the form in the welcome page). Thanks!



Did you find this content useful ?, If so, please consider donating a tip to the author(s). MoonBooks.org is visited by millions of people each year and it will help us to maintain our servers and create new contents.

Amount