How to turn NaN from parseInt into 0 for an empty string?
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
.
Convert NaN to 0 in JavaScript
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.
Javascript parseInt method returns NaN
It seems some of your input have the empty string.
parseInt("")
returns NaN
, you can use Number()
Instead. Converting the empty string with Number()
will give you 0
and you will get the expected result through addition.
Please Note: You can still use parseInt()
by filtering out the inputs with empty values using Attribute Not Equal Selector like the following way:
var count = 0;$("[id^=item-][value!='']").each(function(){ var get_item_amount = $(this).val(); count = parseInt(count) + parseInt(get_item_amount); console.log(count);});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><input class="input item-input" type="text" id="item-1" placeholder="จำนวน" value="11">
<input class="input item-input" type="text" id="item-2" placeholder="จำนวน" value="">
<input class="input item-input" type="text" id="item-3" placeholder="จำนวน" value="33">
parseInt() unexpectedly equating to NaN
In this code, you're setting $textbox
to the value of the text box (or 0):
var $textbox;
if ($('#textbox').val()) {
$textbox = $('#textbox').val();
}
else{
$textbox = 0;
}
And then you have an extra $(...).val()
where you're parsing:
var $textboxParsed = parseInt($($textbox).val(), 10);
// Here ----------------------^^--------^^^^^^^
At that point, since $textbox
has the value from the text box in it, that means you're asking jQuery to create a jQuery object based on that value. That jQuery object will presumably have no elements in it, as searching for (say) $("123")
won't find anything. So when you call val
on it, you get undefined
, because val
on an empty jQuery set gives you undefined
. Then parseInt
then converts that undefined
to the string "undefined"
before trying to parse it — and then gives you NaN
.
You don't want either the $(...)
or the second .val
call:
var $textboxParsed = parseInt($textbox, 10);
Side note: If you want to use 0
for an empty text box, you can use JavaScript's curiously-powerful ||
operator to make that a bit more concise:
var $textbox = $('#textbox').val() || 0;
$textbox
will end up with the value from the textbox if it's not blank, or 0
if it is blank.
(Or use "0"
because you're going to parse it later, but calling parseInt
on something that's already a number is harmless.)
Why does Number('') returns 0 whereas parseInt('') returns NaN
The difference is due in part to Number()
making use of additional logic for type coercion. Included in the rules it follows for that is:
- A StringNumericLiteral that is empty or contains only white space is converted to +0.
Whereas parseInt()
is defined to simply find and evaluate numeric characters in the input, based on the given or detected radix
. And, it was defined to expect at least one valid character.
13) If S contains a code unit that is not a radix-R digit, let Z be the substring of S consisting of all code units before the first such code unit; otherwise, let Z be S.
14) If Z is empty, return NaN.
Note: 'S' is the input string after any leading whitespace is removed.
As
0==''
returnstrue
I believe it interprets like0==Number('')
[...]
The rules that ==
uses are defined as Abstract Equality.
And, you're right about the coercion/conversion that's used. The relevant step is #6:
If Type(x) is Number and Type(y) is String,
return the result of the comparison x == ToNumber(y).
NaN error on ParseInt()
You need to get the content of the runningTotal
element, and then convert that to an integer. getElementById
returns an element object, rather than its contents. This means that your code is trying to convert the element itself (the entire div
) to an integer, rather than convert the contents of the element (0) to an integer.
You can use innerText
to retrieve the contents of the element:
const runningTotal = document.getElementById( 'runningTotal' );
const parsedTotal = parseInt(runningTotal.innerText);
runningTotal.innerHTML = parsedTotal + diceTotal;
Why does Number(null) return 0, and parseFloat(null) return NaN?
parseInt/Float
convert their argument to a string, read it char by char from the left and try to make a number from what they've found. SinceString(null)
is"null"
and a decimal number cannot start with"n"
,parseInt(null)
will beNaN
. If you provide a different base, wheren
,u
andl
are digits, the result will be different:
console.log(parseInt(null, 32))
Javascript calculation returns NaN when input fields are empty
You can use ||0
in combination with your parseInt()
call to make sure that the returned value is always a number and, in the case of empty <input>
field, a 0.
var income1 = document.getElementById("income1");var income2 = document.getElementById("income2");var income3 = document.getElementById("income3");var income4 = document.getElementById("income4");var totalIncome = document.getElementById("totalIncome");
var inputs = Array.prototype.slice.call(document.querySelectorAll("td > input"));
inputs.forEach(function(input) {
input.addEventListener("blur", function() { totalIncome.value = (parseInt(income1.value, 10) || 0) + (parseInt(income2.value, 10) || 0) * 0.7 + (parseInt(income3.value, 10) || 0) / 48 + ((parseInt(income4.value, 10) || 0) * 0.7) / 48; });});
<table> <tr id="row"> <td>No. of Dependant(s)</td> <td><input type="text" id="income1" value=""></td> <td><input type="text" id="income2" value=""></td> <td><input type="text" id="income3" value=""></td> <td><input type="text" id="income4" value=""></td> <td><input type="text" id="totalIncome" readonly></td> </tr></table>
Related Topics
JavaScript Function Order: Why Does It Matter
Leaflet Drawing Tiles Disjointly
Npm Install Cannot Find Module 'Semver'
How to Clone a JavaScript Object Except for One Key
Which Browsers Support Import and Export Syntax for Ecmascript 6
Check If Jquery Has Been Loaded, Then Load It If False
How to Stop Babel from Transpiling 'This' to 'Undefined' (And Inserting "Use Strict")
Array.Length Is Zero, But the Array Has Elements in It
Nodemailer with Gmail and Nodejs
How to Remove a Key from a JavaScript Object
Higher-Order Functions in JavaScript
Does Console.Log Invokes Tostring Method of an Object
How Do Pipes and Monads Work Together in JavaScript
How to Automatically Reload a Page After a Given Period of Inactivity
Javascript: Uncaught Typeerror: Cannot Call Method 'Addeventlistener' of Null
How to Check Whether <Ng-Content> Is Empty? (In Angular 2+ Till Now)