Coder Perfect

What is the best way to convert NaN from parseInt to 0 for an empty string?

Problem

When processing values in JavaScript, is it feasible to return 0 instead of NaN?

If the string is empty, parseInt returns NaN.

Is it feasible to check for NaN in JavaScript in a similar way?

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

Maybe there’s another method or jQuery plugin that can perform the same thing?

Asked by Joper

Solution #1

var s = '';

var num = parseInt(s) || 0;

The logical OR (||) operator delivers the first expression (parseInt(s)) if it can be evaluated to true, else it yields the second expression when not used with boolean values (0). The value returned by parseInt(“) is NaN. Because NaN evaluates to false, num is set to 0.

Answered by Matthew

Solution #2

You can also use the isNaN() function:

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

Answered by gprasant

Solution #3

No one mentioned using Number, which shocked me (). It will parse decimals if they are provided, therefore it will behave differently from parseInt(), although it already assumes base 10 and will convert “” or even ” ” to 0.

Answered by Chris Werner

Solution #4

The problem

Other responses do not account for the fact that 0 is false, hence the following will be 20 instead of 0:

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

The solution

I suggest a helper function that addresses the majority of the problems:

function getNumber({ value, defaultValue }) {
  const num = parseInt(value, 10);
  return isNaN(num) ? defaultValue : num;
}

The following are the outcomes of the helper function:

getNumber({ value: "0", defaultValue: 20 }); // 0
getNumber({ value: "2", defaultValue: 20 }); // 2
getNumber({ value: "2.2", defaultValue: 20 }); // 2
getNumber({ value: "any string", defaultValue: 20 }); // 20
getNumber({ value: undefined, defaultValue: 20 }); // 20
getNumber({ value: null, defaultValue: 20 }); // 20
getNumber({ value: NaN, defaultValue: 20 }); // 20
getNumber({ value: false, defaultValue: 20 }); // 20
getNumber({ value: true, defaultValue: 20 }); // 20

Answered by sqren

Solution #5

You can use the bitwise OR operator if you’re not limited to parseInt (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 that ToInt32 is not the same as parseInt. (For example, parseInt(’33Ab’) === 33)

Answered by Ahmad Ibrahim

Post is based on https://stackoverflow.com/questions/6736476/how-to-turn-nan-from-parseint-into-0-for-an-empty-string