Skip to content

How to convert a string into integer in JavaScript?

In this small post, let’s learn how to convert a String to an Integer in JavaScript. To convert a string to an integer parseInt() and Number() function are used in JavaScript.

parseInt()

The parseInt() function parses a string argument and returns an integer of the specified base number. It’s called radix. Radix is the base in mathematical numeral systems. For Octal, radix is 8. For Hexadecimal, radix is 16.

For our everyday usage we will use 10, because we are doing the decimal system.

parseInt() returns undefined (NaN) if the string is not a number

Examples

let text = '24';
console.log(parseInt(text, 10));
//24
let text = '24in';
console.log(parseInt(text));
//24
let text = 'sdklfjsdkljfklsdinadakljdklsjfklsdjfklsd';
console.log(parseInt(text));
//NaN

Number()

The Number() function converts a string to a number. It will return a number depending on the type i.e integer, float etc. Number() returns undefined if the string cannot be parsed to a number.

Examples

let t = '24';
console.log(Number(t));
//24
let t = '2.48';
console.log(Number(t));
//2.48
let t = '267uiuiouo';
console.log(Number(t));
//NaN

Your primary choice for converting a string to number in JavaScript should be parseInt().

See also  How to represent negative infinity in JavaScript?

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.