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:
- blank string should return NaN (not 0)
- mixed strings (e.g. "3b") should return NaN (not 3)
asked Mar 31, 2011 at 19:03
gap
2,7963 gold badges29 silver badges38 bronze badges
5 Answers 5
function cNum(param) {
return param === "" ? NaN : Number(param)
}
cNum(""); //returns NaN
cNum("3b"); //returns NaN
cNum("4.5"); //returns 4.5
answered Mar 31, 2011 at 19:08
danniel
1,7511 gold badge11 silver badges13 bronze badges
Sign up to request clarification or add additional context in comments.
1 Comment
hammer
you may also check null as it will be treated as 0.
answered Mar 31, 2011 at 19:05
Brian L
11k5 gold badges23 silver badges17 bronze badges
3 Comments
gap
I think, based on other SO Q&A, that parseInt will return "3" when given "3b" and "0" when given "".
Lightness Races in Orbit
Don't link to w3schools please. It's widely regarded as a poor and inaccurate reference.
Brian L
Really? I'll admit I don't do much web development, but I've never run across anything inaccurate there. Do you have an example?
function stringToInt(str) {
var num = parseInt(str);
if (num == str)
return num;
return NaN;
}
Examples
stringToInt("")
NaN
stringToInt("3")
3
stringToInt("3x")
Nan
answered Mar 31, 2011 at 19:06
Jim Blackler
23.3k12 gold badges90 silver badges101 bronze badges
1 Comment
gap
Simple, easy... I like it! Nothing built in though, huh?
var intval = /^\d+$/.test( strval ) ? parseInt( strval ) : NaN;
answered Mar 31, 2011 at 19:08
meouw
42.1k11 gold badges55 silver badges69 bronze badges
Comments
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.
answered Mar 31, 2011 at 19:41
kennebec
105k32 gold badges109 silver badges127 bronze badges
Comments
lang-js