Why does this return NaN? - javascript

model.qty = (parseInt($('#amendOrderQty').val()) == NaN) ?
0 :
parseInt($('#amendOrderQty').val());
// model.qty === NaN when #amendOrderQty is left blank
I am trying to set a value of 0 when the field is left blank. Why does this not work?

You cannot use the comparison operator with NaN, it will always return false.
Use isNaN() instead
var qty = parseInt($('#amendOrderQty').val());
model.qty = isNaN(qty) ? 0 : qty;

Use "isFinite" instead.
var x = parseInt($('#amendOrderQty').val();
model.qty = isFinite(x) ? x : 0;

You cannot directly compare something to NaN because
NaN === NaN
always returns false.
In light of this, you should replace
parseInt($('#amendOrderQty').val()) == NaN
with
isNan(parseInt($('#amendOrderQty').val()))
Your code, refactored and fixed, should look something like this:
var orderQtyVal = parseInt($('#amendOrderQty').val());
model.qty = isNaN(orderQtyVal) ? 0 : orderQtyVal;

Related

Checking and converting some value to number using conditional operator

Given a string stored in a variable 'givenValue'. If it's all numbers, convert the string to number
(e.g. '11' to 11, 'a1' to 'a1')
and assign it to a variable 'value':
const value = givenValue - 0 === NaN ? givenValue : givenValue - 0;
But the output is not what I expected:
const givenValue = 'a1';
console.log(value); // NaN
const givenValue = '1';
console.log(value); // 1
Seems like the value of 'givenValue' is reassigned at the time of the 'if' condition being checked, or the condition check is not working.
You can use isNaN function to check something is NaN or not:
const givenValue = 'a1';
console.log(isNaN(givenValue) ? givenValue : +givenValue);
Also, if you want to check something is numeric or not before casting to a number, you can use isNaN function with isFinite function:
const givenValue = 'a1';
const value = !isNaN(parseFloat(givenValue)) && isFinite(givenValue)
? givenValue : +givenValue;
console.log(value);
Strings that aren't fully numbers but have numeric characters may well return a number other than NaN in many circumstances - see that link for a full description of how the algorithm works. Suffice to say, it's slightly complicated, and isn't what you're looking for. (eg, you'd want '123e456' to fail, but that'd actually give you Infinity instead. Whitespace will be permitted too.) (Also, a === NaN check will always return false, because NaN isn't equal to anything)
Instead, use a regular expression to check that the string contains only digits:
const value = /^\d+$/.test(givenValue) ? Number(givenValue) : givenValue;
If you want to include possible decimal amounts too, then add an optional group of . followed by digits:
const value = /^\d+(?:\.\d+)?$/.test(givenValue) ? Number(givenValue) : givenValue;
// ^^^^^^^^^^
NaN doesn't equal itself. Try like this: givenValue - 0 !== givenValue - 0 ? givenValue : givenValue - 0.
In Javascript, NaN === NaN is alway false.
So you should use isNaN(givenValue - 0) rather than givenValue - 0 === NaN
console.log(NaN === NaN) // false
console.log(NaN == NaN) // false
console.log(isNaN(NaN)) // true
const fixedFunc = (givenValue) => isNaN(givenValue - 0) ? givenValue : givenValue - 0;
console.log(JSON.stringify({
"fixedFunc('a1')": fixedFunc('a1'),
"fixedFunc('1')": fixedFunc('1')
}))
ONLY WORKS WITH NONZERO NUMBERS
A simpler method would be to use const value = givenValue - 0 || givenValue;
var givenValue = '1';
var value = givenValue - 0 || givenValue;
console.log(value);
givenValue = 'a1';
value = givenValue - 0 || givenValue;
console.log(value);

Typescript : check a string for number

I'm new to web development, and in my function want to check if a given string value is a number. In case the string isn't a valid number I want to return null.
The following works for all cases except when the string is "0" in which case it returns null.
parseInt(columnSortSettings[0]) || null;
How do I prevent this from happening. Apparantly parseInt doesn't consider 0 as an integer!
Since 0 is act as false , so you can use isNaN() in this case
var res = parseInt(columnSortSettings[0], 10);
return isNaN(res) ? null : res;
It's because you are basically testing 0 which is also false.
You can do
var n = columnSortSettings[0];
if(parseInt(n, 10) || n === '0'){
//...
}
You can also test instead if it's a number
if(typeof(parseInt(n, 10)) === 'number'){
//...
}
But beware cause
typeof Infinity === 'number';
typeof NaN === 'number';
You can use the isNumeric operator from rxjs library (importing rxjs/util/isNumeric

"Is not a function" error message at string modification with JavaScript?

I'm trying to modify the value of a string given a condition in a ternary operator statement:
($.trim($("#la").val())) ? a = $("#la").val() : a = 'NaN'
However I'm getting the error message:
"NaN" is not a function
What have I got wrong?
You'd generally do that like this
var a = $.trim($("#la").val()).length ? $("#la").val() : NaN;
or in this case, where an empty string would be falsy, you could do
var a = $('#a').val() || NaN;
The issue with NaN not being a function is probably because you quoted it, so it's a string, but unquoting it wont make it a function, it's still a native property!
var a = ($.trim($('#la').val()).length > 0) ? $('#la').val() : 'NaN';
should give you what you want.
Try this one:
var value = $("#la").val();
var a = ($.trim(value).length>0) ? value : 'NaN';

How to parse a number from a text input or assign 0 if it is null?

I'm having trouble with this, even though it seems fairly simple. I have the following jquery snippet that assigns a numeric value from the text input with the id salary to the javascript variable.
If this text field is empty, I would like to assign 0 to the javascript variable, salary.
salary = parseFloat($("#salary").val());
Is there a simple, concise way to do this in javascript?
Try this:
var salary = parseFloat($("#salary").val()) || 0;
parseFloat will return NaN if it is unable to parse the input, and becaue NaN is falsy, you can simply use the || operator:
salary = parseFloat($("#salary").val()) || 0;
If it is unable to parse the input to a valid number (or it is parsed as 0), this will return 0.
try this:
var value = $("#salary").val();
salary = parseFloat(value != '' ? value : 0 );
var a = $("#salary").val();
salary = parseFloat((a!="")?a:0);
you can use Number function
salary = Number($("#salary").val()) == "NaN" ? 0 : Number($("#salary").val());
if(!$.trim($("#salary").val()).length == 0 ) { // zero-length string AFTER a trim
salary = parseFloat($("#salary").val());
}
else{
salary =0;
}

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

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?
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.
You can also use the isNaN() function:
var s = ''
var num = isNaN(parseInt(s)) ? 0 : parseInt(s)
The problem
Other answers don't take into account that 0 is falsy, and thus the following will be 20 instead of 0:
const myNumber = parseInt('0') || 20; // 20
The solution
I propose a helper function, that solves most of the issues:
function getNumber({ value, defaultValue }) {
const num = parseInt(value, 10);
return isNaN(num) ? defaultValue : num;
}
The helper function will give the following results:
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
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.
For people who are not restricted to parseInt, you can use the bitwise OR operator (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: ToInt32 is different from parseInt. (i.e. parseInt('33Ab') === 33)
Does the job a lot cleaner than parseInt in my opinion, Use the +operator
var s = '';
console.log(+s);
var s = '1024'
+s
1024
s = 0
+s
0
s = -1
+s
-1
s = 2.456
+s
2.456
s = ''
+s
0
s = 'wtf'
+s
NaN
Why not override the function? In that case you can always be sure it returns 0 in case of NaN:
(function(original) {
parseInt = function() {
return original.apply(window, arguments) || 0;
};
})(parseInt);
Now, anywhere in your code:
parseInt('') === 0
var value = isNaN(parseInt(tbb)) ? 0 : parseInt(tbb);
//////////////////////////////////////////////////////
function ToInt(x){x=parseInt(x);return isNaN(x)?0:x;}
//////////////////////////////////////////////////////
var x = ToInt(''); //-> x=0
x = ToInt('abc') //-> x=0
x = ToInt('0.1') //-> x=0
x = ToInt('5.9') //-> x=5
x = ToInt(5.9) //-> x=5
x = ToInt(5) //-> x=5
For other people looking for this solution, just use: ~~ without parseInt, it is the cleanest mode.
var a = 'hello';
var b = ~~a;
If NaN, it will return 0 instead.
OBS. This solution apply only for integers
Do a separate check for an empty string ( as it is one specific case ) and set it to zero in this case.
You could appeand "0" to the start, but then you need to add a prefix to indicate that it is a decimal and not an octal number
I had a similar problem (firefox v34) with simple strings like:
var myInt = parseInt("b4");
So I came up with a quick hack of:
var intVal = ("" + val).replace(/[^0-9]/gi, "");
And then got all stupid complicated to deal with floats + ints for non-simple stuff:
var myval = "12.34";
function slowParseNumber(val, asInt){
var ret = Number( ("" + val).replace(/[^0-9\.]/gi, "") );
return asInt ? Math.floor(ret) : ret;
}
var floatVal = slowParseNumber(myval);
var intVal = slowParseNumber(myval, true);
console.log(floatVal, intVal);
It will return 0 for things like:
var intVal = slowParseNumber("b"); // yeilds 0
I created a 2 prototype to handle this for me, one for a number, and one for a String.
// This is a safety check to make sure the prototype is not already defined.
Function.prototype.method = function (name, func) {
if (!this.prototype[name]) {
this.prototype[name] = func;
return this;
}
};
// returns the int value or -1 by default if it fails
Number.method('tryParseInt', function (defaultValue) {
return parseInt(this) == this ? parseInt(this) : (defaultValue === undefined ? -1 : defaultValue);
});
// returns the int value or -1 by default if it fails
String.method('tryParseInt', function (defaultValue) {
return parseInt(this) == this ? parseInt(this) : (defaultValue === undefined ? -1 : defaultValue);
});
If you dont want to use the safety check, use
String.prototype.tryParseInt = function(){
/*Method body here*/
};
Number.prototype.tryParseInt = function(){
/*Method body here*/
};
Example usage:
var test = 1;
console.log(test.tryParseInt()); // returns 1
var test2 = '1';
console.log(test2.tryParseInt()); // returns 1
var test3 = '1a';
console.log(test3.tryParseInt()); // returns -1 as that is the default
var test4 = '1a';
console.log(test4.tryParseInt(0));// returns 0, the specified default value
You can have very clean code, i had similar problems and i solved it by using :
var a="bcd";
~~parseInt(a);
// implicit cast
var value = parseInt(tbb*1); // see original question
Explanation, for those who don't find it trivial:
Multiplying by one, a method called "implicit cast", attempts to turn the unknown type operand into the primitive type 'number'. In particular, an empty string would become number 0, making it an eligible type for parseInt()...
A very good example was also given above by PirateApp, who suggested to prepend the + sign, forcing JavaScript to use the Number implicit cast.
Aug. 20 update: parseInt("0"+expr); gives better results, in particular for parseInt("0"+'str');
Also this way, why not write a function and call it where ever required . I'm assuming it's the entry into the form fields to perform calculations.
var Nanprocessor = function (entry) {
if(entry=="NaN") {
return 0;
} else {
return entry;
}
}
outputfield.value = Nanprocessor(x);
// where x is a value that is collected from a from field
// i.e say x =parseInt(formfield1.value);
what's wrong doing this?
Here is a tryParseInt method that I am using, this takes the default value as second parameter so it can be anything you require.
function tryParseInt(str, defaultValue) {
return parseInt(str) == str ? parseInt(str) : defaultValue;
}
tryParseInt("", 0);//0
tryParseInt("string", 0);//0
tryParseInt("558", 0);//558
an helper function which still allow to use the radix
function parseIntWithFallback(s, fallback, radix) {
var parsed = parseInt(s, radix);
return isNaN(parsed) ? fallback : parsed;
}

Categories

Resources