Proper way to convert number to string in javascript - 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

Related

Remove NaN value, 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');

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.

How to check 2 different types of things using ===?

I want to check whether the value in an input box is equal to a variable. When I use ===, it returns false but when I use ==, it returns true, provided both are equal.
<input id="g1"></input> <button id="b" onclick="myFunction()">Try</button>
function myFunction() {
var d1;
d1 = Math.floor(Math.random()*100)
if( document.getElementById("g1").value == d1) {
document.getElementById("d").innerHTML = "Correct";
}
This happens because JavaScript == can compare numeric strings to numbers whereas === does not.
Similarly the "value" property your using returns a string that you're comparing to an integer. You'll need to use parseInt to convert the value first.
parseInt(document.getElementById("g1").value) === d1
A few things to consider with parseInt:
parseInt returns NaN when you try to convert non-number strings (i.e. converting 'bogus' returns NaN.
It will convert decimals into integers by dropping the decimals. So parseInt('2.1') == 2 // => true.
Honestly, given your use case, it's appropriate to use ==, but I'd add a comment explaining why it's being used.
=== means both value has to be equals but have same type of data in it aswell where == means they only needs to be equal. so for example if d1 is a string holding value 2 and g1 is an integer also holding value 2 using === would not work and will return false as both data is different even though they have same syntax.
<input id="g1"></input> <button id="b" onclick="myFunction()">Try</button>
function myFunction() {
var d1 = 0;
d1 = Math.floor(Math.random()*100)
if( paseint(document.getElementById("g1").value) === d1) {
document.getElementById("d").innerHTML = "Correct";
}
== is the equality operator
=== is an identity operator
For example true==1 is true because true is converted to 1 and then it's compared. However, true===1 is false. This is because it does not do type coercion.
That aside, in your case I think you want to try casting your value to an integer and then compare.
var string5 = '5'
var numb5 = 5
if (string5 == numb5) will return true
if (string5 === numb5) will return false
second variant also compares type, because string is not same type as number it is false.

strings and numbers in comparisons in Javascript

var result='16'>'141';
console.log(result);
var result='16'>141;
console.log(result);
That’s because if any of the operands is not string, then both
operands become numbers, and the comparison becomes correct.
Can anyone tell me. How below equation is evaluate?
var result='a'>11;
console.log(result);
'a'>11=> Answer should be true instead of false;
because
'a' will convert to int 97 > 11 => true then how it evaluate false.
If I go like this 'a'>'11' => then it answer comes true.
var result='a'>'11';
console.log(result);
When you convert a non-numeric string like 'a' to a Number, you get NaN:
console.log(+'a'); // NaN
console.log('a' * 1); // NaN
console.log(Number('a')); // NaN
And NaN always produces false in relational comparisons. Trichotomy does not hold:
console.log(NaN < 0); // false
console.log(NaN > 0); // false
console.log(NaN == 0); // false
If you want to convert 'a' to 97, use charCodeAt:
console.log('a'.charCodeAt(0)); // 97
Javscript use The Abstract Equality Comparison Algorithm
http://www.ecma-international.org/ecma-262/5.1/#sec-11.9.3
When comparing a string and a number, string is converted to a number, but you are thinking like some ASCII code.
Since 'a' is not a number so it's comparison with a number will give you false in any case > , < or ==.

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');

Categories

Resources