Javascript string to integer conversion example

String to Int in javascript

In my previous article, Learned how to doÂ Integer to String convert example. Now we will walk through the String to Integer convert example. String and Integer are basic data types in a javascript programming language. The stringÂ is a valid object if it enclosed either inÂ single quotesÂ orÂ double quotes where integer represents the number.

There are are many ways we can do the conversion.

• Using parseInt function
• Using Number type

Syntax of parseInt() method

parseInt(string object)

and input parameters are stringÂ and radix

string:- is the string object to convert

radix:- it is the base of the number which is going to return as an integer for the string. default radix value is 10.

output always returns valid number, if the number is not valid, it returns NaN value

``````
var numbertype=parseInt('51') // valid and returns 51 as number not string
var numbertype=parseInt("50") // valid and returns 50 as number not string

var numbertype=parseInt("abc") // not valid and returns NaN as abc is not formated number

var num = parseInt("20 25 60"); // valid and returns first string separted by space returned ie 20
var num = parseInt("20,25,60"); // valid and returns first string separted by comma returned ie 20

var num = parseInt("152.99"); // valid and returns  number from floating number

``````

radix is base value in mathematical expressions. Default value is 10.

``````
var numbertype=parseInt('751',10) // valid and returns 7*100+5*10+1(751) as number not string
var numbertype=parseInt('15,8) // valid and returns 1*8+5(13) as number not string

``````

Using Number type

Number(string object)

this Number object converts a string object to a number. The number can be an integer and floating numbers

``````
var numbertype=Number('51') // valid and returns 51 as number not string
var numbertype=Number("50") // valid and returns 50 as number not string
var numbertype=Number("abc") // not valid and returns NaN as abc is not formated number

``````

check if the string is a valid integer or not?

isNaN() is used to check whether a string is a valid number or not

``````
if (isNaN(Number('123string')) {
// This is a string object
}
else {
// It's a number
}

``````
Similar Posts
Subscribe
You'll get a notification every time a post gets published here.

Related posts