javascript parseInt return NaN for empty string

Is it possible somehow to return 0 instead of NaN when parsing values in javascript?

Because in case of if parsed string is empty parseInt returns NaN.

Is it possible to do something like that in JavaScript to check for NaN

 var value = parseInt(tbb) == NaN ? 0 : parseInt(tbb)

Or may be there is some another functions or jQuery plugin which may do something similar?

JavaScript parseInt IE Nan error

I have function in JavaScript: function calc(num) { if (num <= 22) { return parseInt(num); } else { num += ”; var curr = 0; for (var i = 0; i < num[‘length’]; i++) { curr += parseInt(num[i]); }

Problem in getting the parseInt(data) return NaN

I am having a peculiar problem with getting an integer from an ajax response. Whenever I call the following code, parseInt(data) returns NaN despite data being a string. function(data) //return inform

Javascript parseInt always returns NaN [closed]

Can someone tell me why my parseInt function always retuns NaN in the Firebug console despite the string value always returns a number? This is my debug script: console.log($(this).val()+ – +typeof(

JavaScript – Why does my parseInt return NaN? [closed]

var bucketId = $.cookie(‘bucketId’); console.log(bucketId); var bucketIdNumber = parseInt(bucketId, 10); console.log(bucketIdNumber + bucketIdNumber); In the code about bucketId returns 17. So w

Why does parseInt return NAN for “08” string and return 7 for “07” string?

I created a simple apps script as follows: function testeBug() { Logger.log(parseInt(07)); Logger.log(parseInt(08)); } And here’s the logger output: [13-06-19 23:09:13:130 BRT] 7.0 [13-06-19 23:0

NaN !== parseInt(undefined);

How can this be false? console.log(parseInt(undefined)); //NaN console.log(parseInt(undefined)===NaN); //false That seems dumb

javascript parseInt at end of string

I know that parseInt(myString, 10) //never forget ze radix will return a number if the first characters in the string are numerical, but how can I do this in javascript if I have a string like col

Comparing parseInt to NaN in Actionscript 3

The AS3 documentation states that if you pass in a string to parseInt that is not a number it will return NaN. However, when I try to compare to NaN the compiler gives me the following error: Warning:

Javascript parseInt on large negative number gives NaN

When I do this: var x = parseInt(–2147483648); console.log(x); I get the value as: NaN Why does this happen? I want to test if a number is in the range of C (int), so I am doing the above, but it

Why does parseInt(“09”) return 0 but parseInt(“07”) return 7? [duplicate]

Possible Duplicate: Workarounds for JavaScript parseInt octal bug Why does parseInt(09) return 0 but parseInt(07) return 7?

Answers

Do a separate check for an empty string ( as it is one specific case ) and set it to zero in this case.

You could appeand “0” to the start, but then you need to add a prefix to indicate that it is a decimal and not an octal number

var s = '';

var num = parseInt(s) || 0;

Why not override the function? In that case you can always be sure it returns 0 in case of NaN:

(function(original) {
    parseInt = function() {
        return original.apply(window, arguments) || 0;
    };
})(parseInt);

Now, anywhere in your code:

parseInt('') === 0

You can also use the IsNaN() function

var s = ''
var num = isNaN(parseInt(s)) ? 0 : parseInt(s)

Also this way, why not write a function and call it where ever required . I’m assuming it’s the entry into the form fields to perform calculations.

       var Nanprocessor=function(entry){
                        if(entry=="NaN"){
                return 0;

                    }else{ return entry;

                    }


            }

 outputfield.value=Nanprocessor(x); 

//where x is a value that is collected from a from field i.e say x=parseInt(formfield1.value); 

wats wrong doing this?

I was surprised to not see anyone mention using Number(). Granted it will parse decimals if provided, so will act differently than parseInt(), however it already assumes base 10 and will turn “” or even ” ” in to 0.

parseInt(tbb,0);

solves everything 🙂

var warpval0 = j[0][0]["Warping Dept Value"];
                    var warpval1 = j[0][0]["Warping Dept Qty"];
                    warpval0 = warpval0 != "" ? warpval0 : "0";
                    warpval1 = warpval1 != "" ? warpval1 : "0";
                    if (warpval0 > 0 && warpval1 > 0) {
                        $('[id$=ctl00_ContentPlaceHolder1_AvgWarp_Val]')[0].innerHTML = parseInt(Math.round((j[0][0]["Warping Dept Value"]) / (j[0][0]["Warping Dept Qty"])));
                    }
                    else {
                        $('[id$=ctl00_ContentPlaceHolder1_AvgWarp_Val]')[0].innerHTML = "0";
                    }

I had a similar problem (firefox v34) with simple strings like:

var myInt = parseInt("b4");

So I came up with a quick hack of:

var intVal = ("" + val).replace(/[^0-9]/gi, "");

And then got all stupid complicated to deal with floats + ints for non-simple stuff:

var myval = "12.34";

function slowParseNumber(val, asInt){
    var ret = Number( ("" + val).replace(/[^0-9/.]/gi, "") );
    return asInt ? Math.floor(ret) : ret;
}
var floatVal = slowParseNumber(myval);

var intVal = slowParseNumber(myval, true);
console.log(floatVal, intVal);

It will return 0 for things like:

var intVal = slowParseNumber("b"); // yeilds 0

var value = isNaN(parseInt(tbb)) ? 0 : parseInt(tbb);

The problem

Other answers don’t take into account that 0 is falsy, and thus the following will be 20 instead of 0:

var myNumber = parseInt('0') || 20; // 20

The solution

I propose a helper function, that solves most of the issues:

function getNumber(number, defaultNumber) {
    return isNaN(parseInt(number)) ? defaultNumber : parseInt(number, 10);
}

The helper function will give the following results:

getNumber('0', 20); // 0
getNumber('2', 20); // 2
getNumber('2.2', 20); // 2
getNumber('any string', 20); // 20
getNumber(undefined, 20); // 20
getNumber(null, 20); // 20
getNumber(NaN, 20); // 20
getNumber(false, 20); // 20
getNumber(true, 20); // 20

For people who are not restricted to parseInt, you can use the bitwise OR operator (which implicitly calls ToInt32 to its operands).

var value = s | 0;

// NaN | 0     ==>> 0
// ''  | 0     ==>> 0
// '5' | 0     ==>> 5
// '33Ab' | 0  ==>> 0
// '0x23' | 0  ==>> 35
// 113 | 0     ==>> 113
// -12 | 0     ==>> -12
// 3.9 | 0     ==>> 3

Note: ToInt32 is different from parseInt. (i.e. parseInt(’33Ab’) === 33)

//////////////////////////////////////////////////////
function ToInt(x){x=parseInt(x);return isNaN(x)?0:x;}
//////////////////////////////////////////////////////
var x = ToInt('');   //->  x=0
    x = ToInt('abc') //->  x=0
    x = ToInt('0.1') //->  x=0
    x = ToInt('5.9') //->  x=5
    x = ToInt(5.9)   //->  x=5
    x = ToInt(5)     //->  x=5