Monday, July 16, 2018

Javascript string to integer conversion example

String to Int in javascript

Javascript String to Integer convert example
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, 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 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 parameter examples 

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
}


EmoticonEmoticon

Note: Only a member of this blog may post a comment.