Remove NaN value, javascript - javascript

Index 28:
How do I remove this "NaN" value. Cant use isNaN because I want strings and numbers. But not NaN
Tried:
typeof value === 'undefined'
value == null
No success.

You can test for NaN specifically by using Number.isNaN, which is subtly different from plain isNaN: It only returns true if its argument is a number (whose value is NaN). In other words, it won't try to coerce strings and other values to numbers.
Demo:
const values = [
12,
NaN,
"hello",
{ foo: "bar" },
NaN,
null,
undefined,
-3.14,
];
const filtered = values.filter(x => !Number.isNaN(x));
console.log(filtered);
Number.isNaN is new in ECMAScript 6. It is supported by every browser except Internet Explorer. In case you need to support IE, here's a simple workaround:
if (!Number.isNaN) {
Number.isNaN = function (x) { return x !== x; };
}

you can use typeof (to check that's a number) in combination with isNaN
Note that typeof NaN returns "number"
typeof x === "number" && isNaN(x)
Another solution is to use Number.isNaN which will not trying to convert the parameter into a number. So it will return true only when the parameter is NaN

You should be able to use Number.isNaN
console.log([1, "foo", NaN, "bar"].filter((x) => !Number.isNaN(x)))

I’ve seen this comparison check, not sure if you could make it work for you.
var nanValue = NaN;
if(nanValue !== nanValue) // Returns true!
alert('nanValue is NaN');

Related

why do parseInt and isNaN in JavaScript have inconsistent behavior?

I'm using node.js with v8.11.3.
parseInt("") returns NaN, but isNaN("") returns false:
console.log(
parseInt(''),
isNaN('')
);
another example:
console.log(
parseFloat('0x5'),
parseInt('0x5')
);
Per MDN docs, parseInt:
If the first character cannot be converted to a number, parseInt returns NaN.
There is no first character in the empty string - it cannot be converted to a number, so NaN is returned.
But isNaN is different. As the first paragraph of MDN says:
Note: coercion inside the isNaN function has interesting rules; you may alternatively want to use Number.isNaN(), as defined in ECMAScript 2015.
...
When the argument to the isNaN function is not of type Number, the value is first coerced to a Number.
The empty string, when coerced to a Number, is 0:
const result = Number('');
console.log(result + ' : ' + typeof result);
You might try using parseInt and then checking to see if the result is NaN or not:
const possibleInt = parseInt('');
console.log(Number.isNaN(possibleInt));
The use of Number() just shuffles the problem around. For example:
parseInt("14px"); // 14
parseInt("abc"); // NaN
parseInt(""); // NaN (i.e. null string is a number)
versus use of isNaN:
isNaN("14px"); // false
isNaN("abc"); // true
isNaN(""); // false
versus use of Number():
Number("14px"); // NaN
Number("abc"); // NaN
Number(""); // 0
And, making it more complicated, you can't even do:
parseInt(x) == NaN ? 0 : parseInt(x);
because comparisons with NaN are always false, even NaN == NaN is false.
The simplest that I found was:
x=="" || !isNaN(x) ? 0 : parseInt(x);
but this assumes that the null string is the only anomaly, so it may not work in all cases.

Number between double quotes

According to this code
function sayHi(myAge) {
"use strict";
if (isNaN(myAge)) {
return "Ture";
} else {
return "False";
}
}
sayHi("12");
isNan() return false, Why? "12" is not a number.
Because When I do this
var myAge = "12";
alert(myAge === 12);
it will return false, because "12" is a string but 12 a number.
Because NaN is a special value in JS, not a type.
sayHi(NaN) will return true.
If you want to check if the value is the Number type, you should do
if (typeof myAge === "number")
And if you want to be sure, that it's not NaN as well, then
if (typeof myAge === "number" && !isNaN(myAge))
From the spec:
Returns true if the argument coerces to NaN, and otherwise returns false.
Compare to ===:
If Type(x) is different from Type(y), return false.
The isNaN() function determines whether a value is NaN or not. Note: coercion inside the isNaN function has interesting rules; you may alternatively want to use Number.isNaN(), as defined in ECMAScript 6, or you can use typeof to determine if the value is Not-A-Number.
Reference : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isNaN

Proper way to convert number to string in javascript

According to tutorial by w3schools (http://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_tostring_number), we can use toString() method on a integer var. Kindly look at the following code:
var num = 15;
var n = num.toString();
alert(isNaN(n));
If toString() method is working, why isNaN(n) returning false?
The IsNaN method tries converting the string passed to it back to a number, and since "15" is still actually a number, the method returns false.
See: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/isNaN
isNaN() coerces the string '15' into a number value before checking it.
isNaN even coerces booleans, and some falsy values into numbers.
isNaN(true) // >> false
isNaN(false) // >> false
isNaN([]) // >> false
isNaN('') // >> false
Try using typeof to figure out if it's a number or not
var num = 15;
var n = num.toString();
alert(typeof n === 'number');
isNaN() function returns true if the value is NaN, and false if not.
Your code is excute alert(isNaN(15));
So it is return false

What causes isNaN to malfunction? [duplicate]

This question already has answers here:
Validate decimal numbers in JavaScript - IsNumeric()
(52 answers)
Closed 9 years ago.
I'm simply trying to evaluate if an input is a number, and figured isNaN would be the best way to go. However, this causes unreliable results. For instance, using the following method:
function isNumerical(value) {
var isNum = !isNaN(value);
return isNum ? "<mark>numerical</mark>" : "not numerical";
}
on these values:
isNumerical(123)); // => numerical
isNumerical("123")); // => numerical
isNumerical(null)); // => numerical
isNumerical(false)); // => numerical
isNumerical(true)); // => numerical
isNumerical()); // => not numerical
shown in this fiddle: http://jsfiddle.net/4nm7r/1
Why doesn't isNaN always work for me?
isNaN returns true if the value passed is not a number(NaN)(or if it cannot be converted to a number, so, null, true and false will be converted to 0), otherwise it returns false. In your case, you have to remove the ! before the function call!
It is very easy to understand the behaviour of your script. isNaN simply checks if a value can be converted to an int. To do this, you have just to multiply or divide it by 1, or subtract or add 0. In your case, if you do, inside your function, alert(value * 1); you will see that all those passed values will be replaced by a number(0, 1, 123) except for undefined, whose numerical value is NaN.
You can't compare any value to NaN because it will never return false(even NaN === NaN), I think that's because NaN is dynamically generated... But I'm not sure.
Anyway you can fix your code by simply doing this:
function isNumerical(value) {
var isNum = !isNaN(value / 1); //this will force the conversion to NaN or a number
return isNum ? "<mark>numerical</mark>" : "not numerical";
}
Your ternary statement is backward, if !isNaN() returns true you want to say "numerical"
return isNum ? "not numerical" : "<mark>numerical</mark>";
should be:
return isNum ? "<mark>numerical</mark>" : "not numerical";
See updated fiddle:
http://jsfiddle.net/4nm7r/1/
Now that you already fixed the reversed logic pointed out on other answers, use parseFloat to get rid of the false positives for true, false and null:
var isNum = !isNaN(parseFloat(value));
Just keep in mind the following kinds of outputs from parseFloat:
parseFloat("200$"); // 200
parseFloat("200,100"); // 200
parseFloat("200 foo"); // 200
parseFloat("$200"); // NaN
(i.e, if the string starts with a number, parseFloat will extract the first numeric part it can find)
I suggest you use additional checks:
function isNumerical(value) {
var isNum = !isNaN(value) && value !== null && value !== undefined;
return isNum ? "<mark>numerical</mark>" : "not numerical";
}
If you would like treat strings like 123 like not numerical than you should add one more check:
var isNum = !isNaN(value) && value !== null && value !== undefined && (typeof value === 'number');

How do I check if a number evaluates to infinity?

I have a series of Javascript calculations that (only under IE) show Infinity depending on user choices.
How does one stop the word Infinity appearing and for example, show 0.0 instead?
if (result == Number.POSITIVE_INFINITY || result == Number.NEGATIVE_INFINITY)
{
// ...
}
You could possibly use the isFinite function instead, depending on how you want to treat NaN. isFinite returns false if your number is POSITIVE_INFINITY, NEGATIVE_INFINITY or NaN.
if (isFinite(result))
{
// ...
}
In ES6, The Number.isFinite() method determines whether the passed value is a finite number.
Number.isFinite(Infinity); // false
Number.isFinite(NaN); // false
Number.isFinite(-Infinity); // false
Number.isFinite(0); // true
Number.isFinite(2e64); // true
A simple n === n+1 or n === n/0 works:
function isInfinite(n) {
return n === n/0;
}
Be aware that the native isFinite() coerces inputs to numbers. isFinite([]) and isFinite(null) are both true for example.
Perform the plain ol’ comparison:
(number === Infinity || number === -Infinity)
or to save several characters:
Math.abs(number) === Infinity
Why to use this
!(Number.isFinite(number)) breaks on NaN inputs.
Number.POSITIVE_INFINITY and Number.NEGATIVE_INFINITY can be redefined; they are configurable.
Infinity and -Infinity are read-only in the strict mode.
It is the shortest solution.
Actually n === n + 1 will work for numbers bigger than 51 bit, e.g.
1e16 + 1 === 1e16; // true
1e16 === Infinity; // false
I like to use Lodash for a variety of defensive coding reasons as well as readability. ES6 Number.isFinite is great and does not have issues with non-numeric values, but if ES6 isn't possible, you already have lodash, or want briefer code: _.isFinite
_.isFinite(Infinity); // false
_.isFinite(NaN); // false
_.isFinite(-Infinity); // false
_.isFinite(null); // false
_.isFinite(3); // true
_.isFinite('3'); // true
I've ran into a scenario that required me to check if the value is of the NaN or Infinity type but pass strings as valid results. Because many text strings will produce false-positive NaN, I've made a simple solution to circumvent that:
const testInput = input => input + "" === "NaN" || input + "" === "Infinity";
The above code converts values to strings and checks whether they are strictly equal to NaN or Infinity (you'll need to add another case for negative infinity).
So:
testInput(1/0); // true
testInput(parseInt("String")); // true
testInput("String"); // false
You can use isFinite in window, isFinite(123):
You can write a function like:
function isInfinite(num) {
return !isFinite(num);
}
And use like:
isInfinite(null); //false
isInfinite(1); //false
isInfinite(0); //false
isInfinite(0.00); //false
isInfinite(NaN); //true
isInfinite(-1.797693134862316E+308); //true
isInfinite(Infinity); //true
isInfinite(-Infinity); //true
isInfinite(+Infinity); //true
isInfinite(undefined); //true
You can also Number.isFinite which also check if the value is Number too and is more accurate for checking undefined and null etc...
Or you can polyfill it like this:
Number.isFinite = Number.isFinite || function(value) {
return typeof value === 'number' && isFinite(value);
}

Categories

Resources