Issue with using isNaN() - javascript

Actually this is a simple program to check weather the number is divisible by 2 or not divisible by 2 or input given is not a number. According to my information isNaN('berry) should give me true as'berry' is a string but in my code this goes quite wrong.
The code is :
var isNum = function(number) {
// My code goes here!
if (number%2===0){
return true
}
else if (isNaN(number)){
console.log("enter the number not the string");
return number
}
else{
return false
}
};
isNum('berry');
The code above returns me false when I run it. Any help will be appreciated.
This is the screenshot

You can try using parseInt() or parseFloat() to convert variables to their integer or float equivalent before use elsewhere.
You can try using typeof to determine the variable type.
var isNum = function(number) {
var number_parsed = parseFloat( number );
if (isNaN(number) || typeof number == 'string' ){
console.log("enter the number not the string");
return number
} elseif(number_parsed % 2 ===0){
return true
} else{
return false
}
};
isNum('berry');

Your code gives the following output (run it here) and it's correctly working
var isNum = function(number) {
// My code goes here!
if (number%2===0){
return true
}
else if (isNaN(number)){
console.log("enter the number not the string");
return number
}
else{
return false
}
};
isNum('berry');

isNan() returns true when the argument is actually NaN. You provided 'berry', not NaN and so isNan() returns false.
Quoting the documentation:
The isNaN() function determines whether a value is NaN or not.
.
Return value
true if the given value is NaN; otherwise, false.

Related

how to check if a number is a BigInt in javascript

i want to check if a number is a BigInt in a acceptable size if statement
i know there is the solution
function isBigInt(x) {
try {
return BigInt(x) === x; // dont use == because 7 == 7n but 7 !== 7n
} catch(error) {
return false; // conversion to BigInt failed, surely it is not a BigInt
}
}
but i wanted to implement the test directly in my if statement, not in my function
can someone help me with that?
You can use typeof. If the number is a BigInt, the typeof would be "bigint". Otherwise, it will be "number"
var numbers = [7, BigInt(7), "seven"];
numbers.forEach(num => {
if (typeof num === "bigint") {
console.log("It's a BigInt!");
} else if (typeof num === "number") {
console.log("It's a number!");
} else {
console.log("It's not a number or a BigInt!");
}
});
A ternary operator can help you if I understood your question well:
...
const isTernary = BigInt(x) === x ? true : false
...
you will have in your variable "isTernay" either true or false depending on whether your number is a bigint or not.
And a BigInt object is not strictly equal to Number but can be in the sense of weak equality.
0n === 0
// ↪ false
0n == 0
// ↪ true
Visit : https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Global_Objects/BigInt for more about BigInt
An easy solution would simply be (assuming you only work with numbers):
Number.prototype.bigInt = false
BigInt.prototype.bigInt = true
And then you could simply call myNum.bigInt to check.
NOTE: 3.bigInt will not work because 3. is considered a number, so you could do:
(3).bigInt
3 .bigInt
or use it on a variable

How to check if there is a number in prompt because all things are string in prompt?

let b=prompt("");
If in prompt someone enter 4 this will also come as a string, so how will I find that it is a number and not a string.
You can use either isNaN to check whether the input is a number or not
// let a = prompt()
let a = "a"
const isNumber = (num) => !isNaN(parseInt(a))
console.log(isNumber(a))
a = "2";
console.log(isNumber(a))
Please have a look at this:
function isNumber(number) {
return Number.isInteger(number) || !isNaN(parseFloat(number)) && isFinite(number)
}
var result = prompt("Enter your number");
if (!isNumber(result)) {
console.log("This is not a number, Try Entering another.");
}
else {
console.log("This is a number.");
}
First Approach: Use !isNaN()
isNaN(x) returns true if x is not a number so invert it using ! to get true whenever x is a number.
Second Approach: use typecasting
Number(x) will convert str to number and return the number and if x is not a number it will return NaN
b = prompt("")
return !isNaN(b)
This will return true if it is a number

Dosage values are not passing correct through validation

I'm coding a function to validate if a number is a valid dosage. A valid dosage is given by value from 0 to 100 (inclusive range). It looks simple, but there are 3 conditions:
The value is not required, so empty value should return true;
There can exist one optional '%' percent sign at the end;
Decimal places are also optional.
I think I am close to the final function, but there are one test where my function fails, and I don't understand why:
function checkDosage(originalValue) {
var validDosage, isNumeric,
value = originalValue;
isNumeric = function(num) {
return !isNaN(num);
}
// take off percent sign if exists
if (value.slice(-1) == '%') {
value = value.slice(0, -1);
}
// get numeric value
value = parseFloat(value);
// check if it is really a number
isNumeric = isNumeric(value);
// conditional for dosage
validDosage = value >= 0 && value <= 100;
// treatment
if (!originalValue || isNumeric && validDosage) {
return true; // valid
}
return false; // invalid
}
checkDosage(''); // true
checkDosage('0'); // true
checkDosage('%'); // true
checkDosage('-1%'); // false
checkDosage('10.5%'); // true
checkDosage('10%%'); // true ??????? THIS SHOULD BE FALSE
checkDosage('100%'); // true
checkDosage('101%'); // false
Thanks for your time.
The problem is using parseFloat, which discards any trailing characters it finds.
Instead, use Number(string) which will either return you a number or the value NaN (not a number). Then your isNumeric function can be replaced by a call to the built in function isNaN
You're merely checking if the string ends with a %. You aren't checking that there is exactly zero or one %s.
In your percent sign logic, you could do something like this:
if (value.slice(-1) === '%') {
value = value.slice(0, -1);
if (value.slice(-1) === '%') {
return false;
}
}
This will chop off the percent sign. If there's still a percent sign at the end of the string, then that means there was more than one %. So this fails your validation, return false.
EDIT: The reason your existing logic doesn't catch the double % is because if the string was 10%%, and you chopped off the last %, then it'd be 10%. If you call parseFloat('10%'), you'll get back 10, which passes your isNumeric test.

How to tell if "123#231.23" is not a number in javascript?

parseInt("123#231.23") returns 123, which is a number.
There are tons of functions out there to detect if something is a number or not already, but they all depend on parseInt.
What is another generic way of detecting that this is not an integer without using regex?
if (isNaN("123#231.23"))
{
alert("IsNaN - not a number");
}
else
{
alert ("it is a number");
}
I'm assuming that OP need to distinguish if input is a number or not. If input is float or integer looks irrelevant to his problem.
Maybe, I'm wrong...
EDIT:
Alright, to keep everyone happy, integer in javasript is pretty big.
How big integer is in javascript check here.
Asking if something is integer is asking is it a whole number between 9007199254740992 and -9007199254740992. Wholeness of the number you may check using modulus %
$("#cmd").click(function (e) { ChectIfInteger( $("#txt").val() ) });
function ChectIfInteger(myval){
if (isNaN(myval)){
alert("not integer (not number)")
}
else{
//it is a number but it is integer?
if( myval % 1 == 0 ){
if (myval <= 9007199254740992 && myval >= -9007199254740992)
{
alert("it is integer in javascript");
}
else{
alert ("not integer");
}
}
else{
alert("nope, not integer");
}
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="txt"/>
<input type="button" id="cmd" value="test input">
Convert back to String and compare:
String(parseInt("123"))=="123" // true
String(parseInt("123.sdfs"))=="123.sdfs" //false
If you really want to check "for valid integer" you must combine isNaN with something else like this:
function isValidInteger(numberToTest) {
return !(isNaN(numberToTest) || String(parseInt(numberToTest)) !== numberToTest.toString());
}
This will evaluate like:
console.log(isValidInteger('123#231.23')); // false
console.log(isValidInteger('123231.23')); // false
console.log(isValidInteger('12323')); // true
console.log(isValidInteger(1e-1)); // false
console.log(isValidInteger('1e-1')); // false
And this work even with numbers.
Here is PLNKR to test.
I think this is the best way to test for integers:
function isInt(str) {
if (typeof str !== 'number' && typeof str !== 'string') {
return false;
}
return str % 1 === 0;
}
Just note that strings / numbers like "123.0" evaluates to true.
Here's yet another one that doesn't rely on string stuff:
function looksLikeInteger(n) {
return +n == n && +n === ~~n;
}
Probably should be called "looksLikeJavaScriptInteger" because it only works for 32-bit integers. It coerces to numeric with unary + and then checks for equality (so ugly strings and objects are tossed out there) and then checks to make sure that the numeric value doesn't change when coerced to an integer.

isFinite of space giving true value

I am trying to validate a price field. I was trying this:
var productId = document.getElementById("productId");
var productName = document.getElementById("productName");
var productPrice = document.getElementById("price");
alert(isFinite(productPrice.value));
if(isNaN(productPrice.value)||!isFinite(productPrice.value)){
error = document.getElementById("priceError");
error.innerHTML = "Please enter correct value";
productPrice.style.border="thin solid red";
}else{
error = document.getElementById("priceError");
error.innerHTML = "";
}
The line alert is giving me true when the input is space/ multiple spaces only.
This is my HTML page.
<td>Price</td>
<td><input type = "text" id = "price" size = "14"/></td>
Thanks
Why this happens i cant say, but this code should solve the problem
isFinite(parseFloat(" ")) // false
// because -->
parseFloat(" "); // => result NaN
// tested in Chrome 27+ on Win7
in the MDN refernce of isNaN here
it says
isNaN(" "); // false: a string with spaces is converted to 0 which is not NaN
Update:
in the Reference of isFinite found Here it states that isFinite only returns false if the argument is:
NaN
positive infinity, (Number.POSITIVE_INFINITY)
negative infinity (Number.NEGATIVE_INFINITY)
In any other Case it returns true. (like Paul S mentioned)
Now i Think i got all loose ends, and in that course learned something. :)
with window.isFinite, you must be aware of the issues that window.isNaN suffers from when coercing types.
window.IsNaN Summary
Determines whether a value is NaN or not. Be careful, this function is
broken. You may be interested in ECMAScript 6 Number.isNaN.
Examples
isNaN(NaN); // true
isNaN(undefined); // true
isNaN({}); // true
isNaN(true); // false
isNaN(null); // false
isNaN(37); // false
// strings
isNaN("37"); // false: "37" is converted to the number 37 which is not NaN
isNaN("37.37"); // false: "37.37" is converted to the number 37.37 which is not NaN
isNaN(""); // false: the empty string is converted to 0 which is not NaN
isNaN(" "); // false: a string with spaces is converted to 0 which is not NaN
// This is a false positive and the reason why isNaN is not entirely reliable
isNaN("blabla") // true: "blabla" is converted to a number. Parsing this as a number fails and returns NaN
In ECMAScript 6 there are new methods Number.isNaN and Number.isFinite that address these issues. (of course these are not available in many browsers)
Number.isFinite is equivalent to
function isFinite(number) {
return typeof number === "number" && window.isFinite(number);
}
So as a solution, you would need to consider something like this (cross-browser).
Note: this solution will still allow you to enter hexadecimal or scientific notations, "0xA", "1e10"
Javascript
function isFinite(number) {
return typeof number === "number" && window.isFinite(number);
}
function trim(string) {
return string.replace(/^\s+|\s+$/g, "");
}
var price = document.getElementById("price");
price.onchange = function (e) {
var evt = e || window.event,
target = evt.target || evt.srcElement,
value = trim(target.value) || "NaN",
number = +value;
console.log("number:", number);
console.log("isFinite:", isFinite(number));
}
On jsfiddle
You could do it using reqular expression.
Try this.
function validatePrice() {
var el = document.getElementById('price');
if (
el.value.length < 14 &&
/^ *\+?\d+ *$/.test( el.value )
)
{
return true;
}
return false;
}
This function checks if the input is positive integer. I didnt know if you want floated values also.
If you do, switch the regex to this /^ *+?\d+((.|,)\d+)? *$/

Categories

Resources