Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to turn NaN from parseInt into 0 for an empty string?

Tags:

javascript

nan

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

In case of the empty string 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 maybe there is another function or jQuery plugin which may do something similar?

like image 836
Joper Avatar asked Jul 18 '11 16:07

Joper


3 Answers

var s = '';
var num = parseInt(s) || 0;

When not used with boolean values, the logical OR || operator returns the first expression parseInt(s) if it can be evaluated to true, otherwise it returns the second expression 0. The return value of parseInt('') is NaN. NaN evaluates to false, so num ends up being set to 0.

like image 101
Matthew Avatar answered Oct 24 '22 11:10

Matthew


You can also use the isNaN() function:

var s = ''
var num = isNaN(parseInt(s)) ? 0 : parseInt(s)
like image 60
gprasant Avatar answered Oct 24 '22 12:10

gprasant


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.

like image 25
Chris Werner Avatar answered Oct 24 '22 11:10

Chris Werner