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);
Related
I'm trying to do error handling on 2 input values. I'm using regex to confirm that the input is always a number. The issue I'm having is that I don't want my error handling to kick in if the user literally inputs 0. Right now I'm using:
number = parseInt(incomingValue) || ""
to set my variable. The issue is that this turns '0' into ""
Its fine if an empty value becomes an empty string because I am disabling my error checking when the lengths are equal to 0, but I need to properly turn '0' into a number 0. Anyone have any ideas?
Additionally, I'd also like to turn '000' (and so forth) into a number 0
You can turn '0' or '000' into a number by just doing:
parseInt('0'); // 0
parseInt('000'); // 0
The reason your code is not working is that javascript treats 0 as a falsly value, so when you do this:
const number = parseInt('0') || ""
the expression parseInt('0') will return 0 which is falsy. As a result, the || "" will be executed which will set number to "". You'll need to separate your parseInt and your default assignment to achieve what you want.
Use "Number()":
console.log(Number('0'));
console.log(Number('000'));
console.log(typeof(Number('0')));
console.log(typeof(Number('000')));
Or put "+" before '0' and '000':
console.log(+'0');
console.log(+'000');
console.log(typeof(+'0'));
console.log(typeof(+'000'));
Or put "* 1" before or after '0' and '000':
console.log('0' * 1);
console.log('000' * 1);
console.log(typeof('0' * 1));
console.log(typeof('000' * 1));
You can use parseInt(incomingValue) to get the int value.
For comparing you can use === for equal value and equal type means (incomingValue === 0) will be true in case of incomingValue = 0.
You can try typeof to distinguish what type of variable you are receiving
typeof true === 'boolean'
typeof null === 'object'
typeof 62 === 'number'
typeof 'Hello World' === 'string'
Trying to convert string to a number, works fine apart from when the number is zero it returns an empty string;
I understand 0 is false, but I just need a neat way of it returning the string "0"
I'm using:
const num = this.str ? this.str.toString() : '' ;
I even thought of using es6 and simply ${this.str} but that didn't work
Because 0 is "false-y" in JavaScript, as you've already figured out, you can't utilized it in a conditional. Instead, ask yourself what the conditional is really trying to solve.
Are you worried about null / undefined values? Perhaps this is better:
const num = (typeof this.str !== "undefined" && this.str !== null) ? this.str.toString() : "";
Odds are you really only care if this.str is a Number, and in all other cases want to ignore it. What if this.str is a Date, or an Array? Both Date and Array have a .toString() method, which means you may have some weird bugs crop up if one slips into your function unexpectedly.
So a better solution may be:
const num = (typeof this.str === "number") ? this.str.toString() : "";
You can also put your code in a try catch block
const num = ''
try {
num = this.str.toString();
} catch(e) {
// Do something here if you want.
}
Just adding to given answers - if you do:
x >> 0
you will convert anything to a Number
'7' >> 0 // 7
'' >> 0 // 0
true >> 0 // 1
[7] >> 0 // 7
It's a right shift bit operation. You can do magic with this in many real life cases, like described in this article.
In my case, the zero (number) that I wanted to converted to a string (which was the value of an option in a select element) was a value in an enum.
So I did this, since the enum was generated by another process and I could not change it:
let stringValue = '';
if (this.input.enumValue === 0) {
stringValue = '0';
} else {
stringValue = this.input.enumValue.toString();
}
In Javascript, is there any difference between
if(!!isLoaded) and if(Boolean(isLoaded))?
I recently started working on an app where the previous developer did this a lot.
I ran a few tests and they both seem to convert strings "true" and "false" to the Boolean type, which I'm assuming is the main reason for doing this.
If they are indeed the same, what is everyone's opinion on which one is more readable?
Both if (!!isLoaded) and if (Boolean(isLoaded)) will be equivalent to if (isLoaded), as JavaScript only looks for truthy values for if conditions. If you need the specific strings "true" and "false", you'll need to compare to that directly with if (isLoaded === "true").
I personally feel the !! is easier to read. They both convert to boolean though.
However like jaromeda mentioned neither will work for this situation. Both string "true" and "false" result in true since values exist.
Empty String is already treated as negative condition in JS, Indeed,...
The following are treated as negative condition in JS :
0 👉🏼 const v = 0 ; (!v) && doSomething()
Empty string 👉🏼 const v = '' ; (!v) && doSomething() ⬅ ⚠️ Attention please since your question is about casting String to Boolean.
false 👉🏼 const v = false ; (!v) && doSomething()
null 👉🏼 const v = null ; (!v) && doSomething()
undefined 👉🏼 const v = undefined ; (!v) && doSomething()
And those 5 values are equals using == and not equal using ===.
Otherwise , v is treated as positive condition.
let zero = 0 ;
let falseVar = false;
console.log(` zero == falseVar ? `, zero == falseVar);
console.log(` zero === falseVar ? `, zero === falseVar);
let emptyString= ''
console.log(` zero == emptyString ? `, zero == emptyString);
console.log(` zero === emptyString ? `, zero === emptyString);
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
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;