gap
gap

Reputation: 2796

How do I convert a string to an int in Javascript?

how do I convert a string to int in JS, while properly handling error cases?

I want NaN returned when the argument is not really an integer quanityt:

Upvotes: 1

Views: 3085

Answers (5)

kennebec
kennebec

Reputation: 104770

You don't need much- if s is a string:

s%1 will return 0 if s is an integer.

It will return a non-zero number if s is a non-integer number,

and NaN if s is not a number at all.

function isInt(s){
    return (s%1===0)? Number(s):NaN;
}

But although the number returned is an integer, to javascript it is still just a number.

Upvotes: 0

meouw
meouw

Reputation: 42140

var intval = /^\d+$/.test( strval ) ? parseInt( strval ) : NaN;

Upvotes: 0

danniel
danniel

Reputation: 1751

function cNum(param) {
  return param === "" ? NaN : Number(param)
}

cNum(""); //returns NaN
cNum("3b"); //returns NaN
cNum("4.5"); //returns 4.5

Upvotes: 1

Jim Blackler
Jim Blackler

Reputation: 23169

function stringToInt(str) {
  var num = parseInt(str);
  if (num == str)
    return num;
  return NaN;
}

Examples

stringToInt("")
NaN

stringToInt("3")
3

stringToInt("3x")
Nan

Upvotes: 0

Related Questions