{

Different ways to convert string to integer in javascript example


Javascript String to Integer convert example

Learn 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 is enclosed either in single quotes or double quotes where an integer represents the number.

How to Convert String to Integer in javascript?

There are many ways we can do the conversion.

  • Using parseInt function
  • Using Number type

Syntax of parseInt() method

parseInt(string object, radix)

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 that returns as an integer for the string. The default radix value is 10.

output always returns a valid number, if the number is not valid, it returns the 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 parameter examples

radix is the base value in mathematical expressions. The 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() uses 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  
}  

THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

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