var num = "10.00";
if(!parseFloat(num)>=0)
{
alert("NaN");
}
else
{
alert("Number");
}
I want to check if a value is not a float number, but the above code always returns NaN, any ideas what I am doing wrong?
!parseFloat(num) is false so you are comparing false >= 0
You could do this:
if(! (parseFloat(num)>=0))
But it would be more readable to do this:
if(parseFloat(num) < 0)
parseFloat returns either a float or NaN, but you are applying the Boolean NOT operator ! to it and then comparing it to another floating point.
You probably want something more like:
var num = "10.0";
var notANumber = isNaN(parseFloat(num));
Because ! has a higher precedence than >=, so your code does
!parseFloat(num) which is false
Then
>= 0, false is coerced into 0, and 0 >= 0 is true, thus the alert("NaN")
https://developer.mozilla.org/en/JavaScript/Reference/Operators/Operator_Precedence
function isFloat(value) {
if(!val || (typeof val != "string" || val.constructor != String)) {
return(false);
}
var isNumber = !isNaN(new Number(val));
if(isNumber) {
if(val.indexOf('.') != -1) {
return(true);
} else {
return(false);
}
} else {
return(false);
}
}
ref
Related
I have my js code for homework here. I have an if statement that should return -1 in console when the input is not a number but instead of returning -1 it returns NaN. Can anybody help me with this?
function calculateFoodOrder(numAnimals, avgFood) {
// IMPLEMENT THIS FUNCTION!
var total = avgFood*numAnimals;
if ((Number(numAnimals || avgFood) < 0) && (isNaN(numAnimals || avgFood))) {
console.log(-1);
} else {
return total
}
}
calculateFoodOrder()
Default values in your function are 'undefined'. That's why javascript is showing NaN. Define default values to avoid this. For example:
function calculateFoodOrder(numAnimals = 0, avgFood = 0) {
var total = avgFood*numAnimals;
if ((Number(numAnimals || avgFood) < 0) && (isNaN(numAnimals || avgFood))) {
console.log(-1);
} else {
return total;
}
}
If I understand your task correctly, you merely have to check both parameters for not being NaN using isNaN.
Your sample code does not work because any comparison with NaN returns false and thus Number(numAnimals || avgFood) < 0 is never going to be true. Check here for details on NaN.
function calculateFoodOrder(numAnimals, avgFood){
//REM: Default result
let tResult = -1;
//REM: Check if both paramters are not NaN
//REM: Be aware that whitespaces and empty strings validate to zero
if(
!isNaN(numAnimals) &&
!isNaN(avgFood)
){
tResult = Number(avgFood) * Number(numAnimals)
};
return tResult
};
//REM: Default test case
console.log(calculateFoodOrder());
;document.querySelector('button').onclick = function(){
console.log(
calculateFoodOrder(
document.getElementById('innumAnimals').value,
document.getElementById('inavgFood').value
)
)
};
<input type = 'text' value = '' id = 'innumAnimals' placeholder = 'numAnimals' />
<input type = 'text' value = '' id = 'inavgFood' placeholder = 'avgFood' />
<button>do</button>
Please do not confuse yourself with caveats if you are a beginner. You should assign to itself after converting to number, then judge if it's a NaN value or less then zero just like this,
function calculateFoodOrder(numAnimals, avgFood) {
// IMPLEMENT THIS FUNCTION!
numAnimals = Number(numAnimals);
avgFood = Number(avgFood);
var total = avgFood * numAnimals;
if (isNaN(numAnimals) || isNaN(avgFood) || numAnimals < 0 || avgFood < 0 ) {
console.log(-1);
} else {
return total
}
}
calculateFoodOrder()
Ive been doing the 'Numerical Palindrome #1' Kata in codewars and I feel like this code should work, but its saying that palindrome(1221) is coming back as false - when obviously it should be coming back as true. if anyone can see why this would be happening i would greatly appreciate it! the challenge said that if num was less than 0, or wasnt an integer then it should return 'not valid'.
function palindrome(num) {
if(typeof num == 'number'){
if(Number.isInteger(num) && num>=0){
return(toString(num) === toString(num).split('').reverse().join(''));
}
else{return 'Not valid';
}
}
else { return 'Not valid';
}
}
toString is a method of Number.prototype so you call it from the number:
function palindrome(num) {
if (typeof num == 'number') {
if (Number.isInteger(num) && num >= 0) {
return (num.toString() === num.toString().split('').reverse().join(''));
} else {
return 'Not valid';
}
} else {
return 'Not valid';
}
}
console.log(palindrome(500))
console.log(palindrome(505))
There was some problem with your code.
you need to use toString() like below :
num.toString()
and also you don't need two if for checking your conditions, you can do it with only 1 if.
I update your code :
var a = function palindrome(num) {
if(typeof num == 'number' && Number.isInteger(num) && num>=0)
return(num.toString() === num.toString().split('').reverse().join(''));
else
return 'Not valid';
}
console.log(a(1001));
https://jsfiddle.net/emilvr/qkz5ypq9/
toString method that you are using will return toString(123456) = "[object Undefined]" . & toString(123456).split('').reverse().join('') = "]denifednU tcejbo[" and hence it is failing. to convert a number to string best is to concatenate it with "", like 12345+"";
You should use String instead of toString.
function palindrome(num) {
if (typeof num == 'number' && Number.isInteger(num) && num >= 0) {
return (String(num) === String(num).split('').reverse().join(''));
}
return 'Not valid';
}
I'm attempting to write a filter for use in a grid that will catch all null, undefined, blank string, or other similar values and display a dash "-". I've written the following so far, but it doesn't catch null values, and I'm wondering if it could be more succinct and possibly refactored to avoid three layers of nested if/else statements. Percentage values need to be checked that they're over 0 and under 1. Also, negative numbers and 0's should be returned as is. Thanks!
angular.module('AdverseEventsExplorer.main').filter('emptyCellFilter', function ($filter) {
return function (input, cellFilter, args1, args2) {
if (cellFilter == undefined) {
return (angular.isNumber(input) || angular.isDefined(input) && input.length > 0) ? input : '-';
} else {
if (cellFilter.match(/pctg|percent|pctgFilter|incidence/ig)) {
return (input > 0 && input < 1.0000000) ? $filter(cellFilter)(input, args1, args2) : '-';
} else {
return (angular.isNumber(input) || angular.isDefined(input) && input.length > 0) ? input : '-';
}
}
};
});
Version 2.0 taking into account #tymeJV's comment:
angular.module('AdverseEventsExplorer.main').filter('emptyCellFilter', function ($filter) {
return function (input, cellFilter, args1, args2) {
if (!cellFilter) {
return (angular.isNumber(input) || (input)) ? input : '-';
} else {
if (cellFilter.match(/pctg|percent|pctgFilter|incidence/ig)) {
return (input > 0 && input < 1.0000000) ? $filter(cellFilter)(input, args1, args2) : '-';
} else {
return (angular.isNumber(input) || (input)) ? $filter(cellFilter)(input, args1, args2) : '-';
}
}
};
});
Whenever you encounter a function that's getting too complex to refactor try extracting some of the smaller statements to concisely named variables. It makes it much easier for our brains to keep track of the function's requirements, and it's also more readable to new devs reading your code.
var inputHasValue = angular.isNumber(input) || input;
if(!inputHasValue){
return '-';
}
if (!cellFilter) {
return input;
}
var isPercentageCell = cellFilter.match(/pctg|percent|pctgFilter|incidence/ig);
var valueIsInRange = input > 0 && input < 1;
if(!isPercentageCell || valueIsInRange){
return $filter(cellFilter)(input, args1, args2);
}
return '-';
typeof x ==='number' || !!x
is false when x is null, undefined or empty string
Only one case in which it doesn't work – if you need to filter boolean variables, but your case doesn't seem to need it.
Anyway in that case you can use
typeof x === 'boolean' || typeof x ==='number' || !!x
I'm checking for integer values in node.js using IsNaN function.
Unexpectedly, this function validates the strings like 1E267146, 1E656716 , 914E6583 to be numbers, as these strings are exponential values. Any way to work around this? In actual scenario i wont get any exponential values.
ECMA6 defines Number.isInteger as follows:
Javascript
function isInteger(nVal) {
return typeof nVal === "number" && isFinite(nVal) && nVal > -9007199254740992 && nVal < 9007199254740992 && Math.floor(nVal) === nVal;
}
but this will also accept scientific notation
console.log(isInteger(1e6));
console.log(isInteger(+"1e6"));
jsfiddle
You need to be clear as to what your definitions/expectations are.
My guess is that you may want something like this, if you are testing strings and have no limits on the max or min integer.
Javascript
function isStringNumericalInteger(testValue) {
return typeof testValue === "string" && /^[\-+]?[1-9]{1}\d+$|^[\-+]?0$/.test(testValue);
}
console.log(isStringNumericalInteger("9007199254740991"));
console.log(isStringNumericalInteger("-123216848516878975616587987846516879844651654847"));
console.log(isStringNumericalInteger("1.1"));
console.log(isStringNumericalInteger("-1.1"));
console.log(isStringNumericalInteger("1e10"));
console.log(isStringNumericalInteger("010"));
console.log(isStringNumericalInteger("0x9"));
console.log(isStringNumericalInteger(""));
console.log(isStringNumericalInteger(" "));
console.log(isStringNumericalInteger());
console.log(isStringNumericalInteger(null));
console.log(isStringNumericalInteger([]));
console.log(isStringNumericalInteger({}));
Output
true
true
false
false
false
false
false
false
false
false
false
false
false
jsfiddle
If you want to bound the range to what javascript can represent numerically as an integer then you will need to add a test for && +testValue > -9007199254740992 && +testValue < 9007199254740992
If you don't like using RegExs, you can also accomplish this with a parser. Something like this:
Javascript
function isCharacterDigit(testCharacter) {
var charCode = testCharacter.charCodeAt(0);
return charCode >= 48 && testCharacter <= 57;
}
function isStringNumericalInteger(testValue) {
var start = 0,
character,
index,
length;
if (typeof testValue !== "string") {
return false;
}
character = testValue.charAt(start);
if (character === "+" || character === "-") {
start += 1;
character = testValue.charAt(start);
}
start += 1;
length = testValue.length;
if ((length > start && character === "0") || !isCharacterDigit(character)) {
return false;
}
for (index = start; index < length; index += 1) {
if (!isCharacterDigit(testValue.charAt(index))) {
return false;
}
}
return true;
}
jsfiddle
I would use something like below code to validate number input. First I parse the given value to float and then check isNaN().
var isNumber = function (obj) {
return !isNaN(parseFloat(obj)) && isFinite(obj);
};
I think this is what you need in your case (i hate regex because this is not very good for the performance but..)
http://jsbin.com/EQiBada/1/
var NMAX = Math.pow(2, 53);
function isNumeric(n) {
n = n < 0 ? n * -1 : n;
var r = /^\d+$/.test(n);
if (r === true)
{
return parseInt(n, 10) >= (NMAX * -1) + 1 && parseInt(n, 10) <= NMAX;
}
return false;
}
Minified
var NMAX = Math.pow(2, 53);
function isNumericMin(n) {
n = n < 0 ? n * -1 : n;
return /^\d+$/.test(n) === true ? parseInt(n, 10) >= (NMAX * -1) + 1 && parseInt(n, 10) <= NMAX : false;
}
var i = '1E267146'
if(isNaN(i) || !isFinite(i) !! i=="")
{
// do stuff
}
else
{
// do stuff
}
I’d like use jquery function that validate a input field. This input field must be used for entering 11 digit numbers that start with 0.
I tried some function but doesn’t work!
function check(mob) {
var firstnum = mob.substring(1);
alert(firstnum);
if (firstnum != "0" || mob.lenght != 11)
return false;
else
return true;
}
function check(mob) {
return mob.substring(0, 1) == '0' && mob.length == 11;
}
String Method Reference
If you want to check is it 11 digit, you should use RegExp
function check(mob) {
return mob.match(/^0\d{10}$/) != null;
}
You need to use .charAt(0) to get the first character of a string. .substring(1) will return the rest of the string minus the first character.
"01234567890".substring(1) = "1234567890"
"01234567890".charAt(0) = "0"
"01234567890".length = 11 (assuming that you have spelled "length" correctly in your code)
Edit: Since you also need to check for digits, you could use a regular expression to verify this (although the whole check could also be done with a regex)
The completed function could therefore be simplified to just:
function isValidMobile(mobileNumber) {
return mobileNumber.charAt(0) == 0 && mobileNumber.length === 11 && /^\d+$/.test(mobileNumber);
}
Or without the regex
function isValidMobile(mobileNumber) {
return mobileNumber.charAt(0) == 0 && mobileNumber.length === 11 && !isNaN(mobileNumber);
}
if (firstnum >= 1 || mob.lenght <= 11) //lenght spell wrong
change to
if (firstnum >= 1 || mob.length<= 11)
you can give it a try
function check(mob) {
var num = parseInt(mob);
if (mob+'' == '0'+num && mob.length == 11)
return true;
else
return false;
}
here what I am doing is that parseInt will give you exact same number without 0 if all characters are numbers, so in the condition I am just adding 0 in starting and checking with mobile number , it will do 2 validation in once , all are number starts with 0 and next validation is for length
Try using a simple regex as below
function check(mob) {
return /^0\d{10}$/.test(mob)
}
function check(mob) {
if(!isNaN(mob)){ // or use parseInt
var firstnum = mob.charAt(0);
alert(firstnum);
if (firstnum != "0" || mob.length != 11) {
return false;
} else {
return true;
}
}
}