Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return Zero if input value is NaN [duplicate]

Is there a best way to prevent NaN? I have number input field that whenever I clear the field, I get NaN.

_amount: function(e) {
  var value = parseInt(e.target.value);
  var newValue = (value === NaN ? 0 : value); // Thought this could work
},

<input type="number" value={this.state.amount} onChange={this_amount} />

Now in my render I have 400 - this.state.amount. The things is, when I clear the input field, amount state is null. How to prevent this? Is it possible that when I clear the field I get zero? Say I type in 3 then clear the field, NaN pops up.

Thanks

like image 901
Sylar Avatar asked May 19 '26 03:05

Sylar


2 Answers

NaNis never equals to anything including NaN itself hence rely on Number.isNaN(value) method.

_amount: function(e) {
  var value = parseInt(e.target.value);
  var newValue = (isNaN(value) ? 0 : value);

  //OR sorthand as `NaN` is falsey
  var value = parseInt(e.target.value) || 0;
}

The necessity of an isNaN function

Unlike all other possible values in JavaScript, it is not possible to rely on the equality operators (== and ===) to determine whether a value is NaN or not, because both NaN == NaN and NaN === NaN evaluate to false. Hence, the necessity of an isNaN function.[Ref]

like image 182
Rayon Avatar answered May 20 '26 15:05

Rayon


The shortest way I found was

var number = (yourVariable || 0)

Because NaN is a falsey value, this will return 0 whenever yourVariable is NaN.

A way to check, if a number is NaN or not is to use the isNaN function.

isNaN(yourVariable); // Returns true is yourVariable is NaN

Side note:

The above method can be used for multiple problems too. For example: getting a value from an array (wich may not exist) and getting a value from a 2d array.

Getting value from array:

yourArray[i] || 0

Where i is the id you want to access

Getting value from a 2D array:

(yourArray[i] || [])[j] || 0

Where i and j are the position of the element in the array

like image 26
Bálint Avatar answered May 20 '26 17:05

Bálint