320

Is there a way to convert NaN values to 0 without an if statement? Example:

if (isNaN(a)) a = 0;

It is very annoying to check my variables every time.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Tamás Pap
  • 17,777
  • 15
  • 70
  • 102

11 Answers11

754

You can do this:

a = a || 0

...which will convert a from any "falsey" value to 0.

The "falsey" values are:

  • false
  • null
  • undefined
  • 0
  • "" ( empty string )
  • NaN ( Not a Number )

Or this if you prefer:

a = a ? a : 0;

...which will have the same effect as above.


If the intent was to test for more than just NaN, then you can do the same, but do a toNumber conversion first.

a = +a || 0

This uses the unary + operator to try to convert a to a number. This has the added benefit of converting things like numeric strings '123' to a number.

The only unexpected thing may be if someone passes an Array that can successfully be converted to a number:

+['123']  // 123

Here we have an Array that has a single member that is a numeric string. It will be successfully converted to a number.

Donald Duck
  • 8,409
  • 22
  • 75
  • 99
user113716
  • 318,772
  • 63
  • 451
  • 440
47

Using a double-tilde (double bitwise NOT) - ~~ - does some interesting things in JavaScript. For instance you can use it instead of Math.floor or even as an alternative to parseInt("123", 10)! It's been discussed a lot over the web, so I won't go in why it works here, but if you're interested: What is the "double tilde" (~~) operator in JavaScript?

We can exploit this property of a double-tilde to convert NaN to a number, and happily that number is zero!

console.log(~~NaN); // 0

Community
  • 1
  • 1
WickyNilliams
  • 5,218
  • 2
  • 31
  • 43
  • 2
    Thanks, i didn't know about this `~~` at all, I just used it along side with `parseFloat()` like so: `~~parseFloat($variable);`. Very neat :) +1 – Rens Tillmann May 13 '18 at 22:48
  • 1
    *WARNING*: `~~20000000000` gives `-1474836480` – sidney Jan 11 '22 at 09:31
  • 1
    Heads up, `parseFloat(4.567)` returns `4.567` but `~~parseFloat(4.567)` returns `4` so it loses the fractional part along with the decimal point. – Baz Guvenkaya May 05 '22 at 00:18
31

Write your own method, and use it everywhere you want a number value:

function getNum(val) {
   if (isNaN(val)) {
     return 0;
   }
   return val;
}
hwcverwe
  • 5,287
  • 7
  • 35
  • 63
Saket
  • 45,521
  • 12
  • 59
  • 79
  • 1
    If I pass in `null` then it does not give me the expected result of `0`. More on my point here: http://stackoverflow.com/questions/115548/why-is-isnannull-false-in-js – Andrei Bazanov Mar 15 '17 at 15:52
  • 2
    Further to my comment above, I ended up using `Number(val)` instead as it returns `0` when it can't figure it out anyhow. – Andrei Bazanov Mar 15 '17 at 15:59
  • @AndreiBazanov OP asks for "convert NaN to 0". While `null` is not `NaN`, why would you expecting it results 0? – tsh Jan 16 '23 at 09:20
  • @tsh because this is JS we are dealing with, anything is possible :) – Andrei Bazanov Jan 18 '23 at 12:32
12

Something simpler and effective for anything:

function getNum(val) {
   val = +val || 0
   return val;
}

...which will convert a from any "falsey" value to 0.

The "falsey" values are:

  • false
  • null
  • undefined
  • 0
  • "" ( empty string )
  • NaN ( Not a Number )
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Woold
  • 783
  • 12
  • 23
  • 1
    Interesting! Just wondering how it reacts when val can be a negative value. As far as I've tested there is nothing wrong with this, but just in case... – Luciano Apr 19 '20 at 02:38
3

Rather than kludging it so you can continue, why not back up and wonder why you're running into a NaN in the first place?

If any of the numeric inputs to an operation is NaN, the output will also be NaN. That's the way the current IEEE Floating Point standard works (it's not just Javascript). That behavior is for a good reason: the underlying intention is to keep you from using a bogus result without realizing it's bogus.

The way NaN works is if something goes wrong way down in some sub-sub-sub-operation (producing a NaN at that lower level), the final result will also be NaN, which you'll immediately recognize as an error even if your error handling logic (throw/catch maybe?) isn't yet complete.

NaN as the result of an arithmetic calculation always indicates something has gone awry in the details of the arithmetic. It's a way for the computer to say "debugging needed here". Rather than finding some way to continue anyway with some number that's hardly ever right (is 0 really what you want?), why not find the problem and fix it.

A common problem in Javascript is that both parseInt(...) and parseFloat(...) will return NaN if given a nonsensical argument (null, '', etc). Fix the issue at the lowest level possible rather than at a higher level. Then the result of the overall calculation has a good chance of making sense, and you're not substituting some magic number (0 or 1 or whatever) for the result of the entire calculation. (The trick of (parseInt(foo.value) || 0) works only for sums, not products - for products you want the default value to be 1 rather than 0, but not if the specified value really is 0.)

Perhaps for ease of coding you want a function to retrieve a value from the user, clean it up, and provide a default value if necessary, like this:

function getFoobarFromUser(elementid) {
        var foobar = parseFloat(document.getElementById(elementid).innerHTML)
        if (isNaN(foobar)) foobar = 3.21;       // default value
        return(foobar.toFixed(2));
}
Chuck Kollars
  • 2,135
  • 20
  • 18
3

I suggest you use a regex:

const getNum = str => /[-+]?[0-9]*\.?[0-9]+/.test(str) ? parseFloat(str) : 0;

The code below will ignore NaN to allow a calculation of properly entered numbers:

const getNum = str => /[-+]?[0-9]*\.?[0-9]+/.test(str) ? parseFloat(str) : 0;

const inputsArray = [...document.querySelectorAll('input')];

document.getElementById("getTotal").addEventListener("click", () => {
  let total = inputsArray.map(fld => getNum(fld.value)).reduce((a,b)=>a+b);
  console.log(total)
});
<input type="text" />
<input type="text" />
<input type="text" />
<input type="text" disabled />
<button type="button" id="getTotal">Calculate</button>
mplungjan
  • 169,008
  • 28
  • 173
  • 236
3

Methods that use isNaN do not work if you're trying to use parseInt(). For example,

parseInt("abc"); // NaN
parseInt(""); // NaN
parseInt("14px"); // 14

But in the second case, isNaN produces false (i.e., the null string is a number).

n="abc"; isNaN(n) ? 0 : parseInt(n); // 0
n=""; isNaN(n) ? 0: parseInt(n); // NaN
n="14px"; isNaN(n) ? 0 : parseInt(n); // 14

In summary, the null string is considered a valid number by isNaN, but not by parseInt(). It was verified with Safari, Firefox and Chrome on macOS v10.14 (Mojave).

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
David Crowe
  • 113
  • 6
  • 1
    One obvious solution is a bit cumbersome, check for NaN after parseInt, not before: isNaN(parseInt(n)) ? parseInt(n) : 0; // calls parseInt twice :( – David Crowe Jan 15 '20 at 23:30
  • 1
    that comment should be (the beginning of) your answer! – frandroid Jan 16 '20 at 00:14
  • A more efficient solution assumes that the null string is the only anomaly: n=="" || isNaN(n) ? 0 : parseInt(n); (but what if there are other strings?) – David Crowe Jan 16 '20 at 01:45
2

NaN is the only value in JavaScript which is not equal to itself, so we can use this information in our favour:

const x = NaN;
let y = x!=x && 0;
y = Number.isNaN(x) && 0

We can also use Number.isNaN instead of the isNaN function as the latter coerces its argument to a number

isNaN('string')        // true which is incorrect because 'string'=='string'
Number.isNaN('string') // false
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Akash Singh
  • 547
  • 5
  • 8
  • Why is "NaN" weirdly syntax highlighted? Is the syntax highlighter correct or not? – Peter Mortensen Apr 20 '22 at 23:36
  • [It is probably the syntax highlighter that is broken](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/NaN) - *"The global NaN property is a value representing Not-A-Number. ... NaN is a property of the global object."*. Why, oh, why? What about using "Number.NaN"? – Peter Mortensen Apr 20 '22 at 23:38
1

    var i = [NaN, 1,2,3];

    var j = i.map(i =>{ return isNaN(i) ? 0 : i});
    
    console.log(j)
Ran Marciano
  • 1,431
  • 5
  • 13
  • 30
KARTHIKEYAN.A
  • 18,210
  • 6
  • 124
  • 133
  • An explanation would be in order. E.g., what is the idea/gist? From [the Help Center](https://stackoverflow.com/help/promotion): *"...always explain why the solution you're presenting is appropriate and how it works"*. Please respond by [editing (changing) your answer](https://stackoverflow.com/posts/43090824/edit), not here in comments (***without*** "Edit:", "Update:", or similar - the answer should appear as if it was written today). – Peter Mortensen Apr 20 '22 at 23:27
1

Please try this simple function

var NanValue = function (entry) {
    if(entry=="NaN") {
        return 0.00;
    } else {
        return entry;
    }
}
Donald Duck
  • 8,409
  • 22
  • 75
  • 99
subindas pm
  • 2,668
  • 25
  • 18
  • An explanation would be in order. E.g., what is the idea/gist? How and why is it different from previous answers (some use isNaN())? What input does it fail for? From [the Help Center](https://stackoverflow.com/help/promotion): *"...always explain why the solution you're presenting is appropriate and how it works"*. Please respond by [editing (changing) your answer](https://stackoverflow.com/posts/45975461/edit), not here in comments (***without*** "Edit:", "Update:", or similar - the answer should appear as if it was written today). – Peter Mortensen Apr 20 '22 at 23:29
0

Using user113716's solution, which by the way is great to avoid all those if-else, I have implemented it this way to calculate my subtotal textbox from textbox unit and textbox quantity.

In the process writing of non-numbers in unit and quantity textboxes, their values are being replaced by zero, so the final posting of user data has no non-numbers.

<script src="/common/tools/jquery-1.10.2.js"></script>
<script src="/common/tools/jquery-ui.js"></script>

<!--------- link above two lines to your jQuery files ------>

<script type="text/javascript">
    function calculate_subtotal(){
        $('#quantity').val((+$('#quantity').val() || 0));
        $('#unit').val((+$('#unit').val() || 0));

        var calculated = $('#quantity').val() * $('#unit').val();
        $('#subtotal').val(calculated);
    }
</script>

<input type = "text" onChange ="calculate_subtotal();" id = "quantity"/>
<input type = "text" onChange ="calculate_subtotal();" id = "unit"/>
<input type = "text" id = "subtotal"/>
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
webzy
  • 338
  • 3
  • 12