Javascript number comparison with negative value doesn't work - javascript

I try to compare a negative value with "0" and that doesn't seem to work.
var number = Number.parseInt($(this).val());
var min = Number.parseInt($(this).attr('min'));
var max = Number.parseInt($(this).attr('max'));
Here's my condition :
if (min && $(this).prop('required')) {
if (number < min) {
alert('ok');
fail = true;
}
}
My min value is 0 and my number is -1.
It never enters the condition. Why?

0 is a falsy value. It will never enter the if condition if min is 0 .
All the following conditions will be sent to else blocks
if (false)
if (null)
if (undefined)
if (0)
if (NaN)
if ('')
if ("")
if (``)
Since the return value of parseInt is either a number or NaN, you can use isNaN instead:
if(!isNaN(min) && $(this).prop('required')) {
// your code
}

Since min is 0, your condition evaluates to false. You have two options, one is to check the string value before parsing it:
if($(this).attr('min').trim() && $( this ).prop('required')) {
if (number < min) {
alert('ok');
fail = true;
}
}
The other is to check for NaN after parsing the number since parsing an empty string will return NaN:
if(!isNaN(min) && $( this ).prop('required')) {
if (number < min) {
alert('ok');
fail = true;
}
}
console.log(' '.trim() == false);
console.log(!isNaN(Number.parseInt('')) == false);

Your condition:
if(min && $( this ).prop('required'))
Would evaluate to false since min has a value of 0 and 0 && anything would be false

(0 && true ) return zero in JavaScript.
see first comment for more details

Related

JavaScript Weird behavior in a condition

there's something that i just solved but I don't understand why i got that kind of behavior, here's my js code
function fibonacci () {
let fibonacciNumber = document.getElementById("my-input").value;
let numberInitialize = 0;
let numberNext = 1;
let sum = numberInitialize + numberNext;
if (fibonacciNumber === "" || fibonacciNumber === 0) {
return (0);
}
for (index = 1; index < fibonacciNumber; index++)
{
numberInitialize = numberNext;
numberNext = sum;
sum = numberInitialize + numberNext;
console.log(sum);
console.log("premier tour");
}
console.log(sum);
document.getElementById("fibo-result").innerHTML = `${sum}`;
}
So on the html side I just have an input and im writing down number, my questions concerned this line of code
if (fibonacciNumber === "" || fibonacciNumber === 0) {
return (0);
}
when im writing down 0, its still printing one but i write the condition like that
if (fibonacciNumber === "" || fibonacciNumber <= 0) {
return (0);
}
its working and when I got 0 as an input nothing is printed like i wanted, my question is: Why when im putting fibonacciNumber === 0 return (0) its not working properly its 0, the condition match no ?
Thanks guys
The reason is because your field actually has the string "0". The identity operator (===) will not do any type coercion before comparing the values, so "0" === 0 is false.
Numeric comparison operators like <= will do type coercion, so "0" <= 0 will evaluate to true.
You can see this all in action below.
console.log("0" === 0);
console.log("0" <= 0);
You will need to use parseInt() and then treat the input as integer.
let fibonacciNumber = parseInt(document.getElementById("my-input").value);

If statement is acting weird for some reason

So I have an if statement that is checking the values of a drop down. The user has to select at least one of them to continue. The values are just numbers. My if statement checks to see that, basically, the values are equal to zero:
if (numChildren === 0 && numAdults === 0){
Than do this
}
But for some reason it keep returning false. I have console logged the numChildren and adults to see what there values are and they are zero I have no idea why it isn't working I have put a "!" before it to cause it to be true but then it remains false. It is a very weird error.
$("#Discounts").on("click", function () {
let numChildren = $("#children").val();
let numAdults = $("#adults").val();
console.log("Adults: " + numAdults + "\nChildren: " + numChildren);
console.log(numChildren === 0 && numAdults === 0);
if (numChildren === 0 && numAdults === 0) {
alert("You must select");
$("#children").val(1);
}
});
When you use 3 equals in a if statement the numChildren must be the same type and value as 0 (integer), not just equal to 0.
Try changing to 2 equals:
if (numChildren == 0 && numAdults == 0) {
alert("You must select");
$("#children").val(1);
}
Reference
It's not weird.
You are using the triple equal comparison and, probably, the numChildren contains a number in string form (like "0") which you are comparing to zero as an actual number.
It should work with:
numChildren == 0 && numAdults == 0
or
Number(numChildren) === 0 && Number(numAdults) === 0
This is the official reference: https://tc39.github.io/ecma262/#sec-strict-equality-comparison
You can try this:
if (Number(numChildren) === 0 && Number(numAdults) === 0) {
alert("You must select");
$("#children").val(1);
}

How do I display the error message only when min and max value exist?

I have created a function that return the min and max value, if the user selects" between" or just the min or max based on the operator the user selects.
When the user selects the "between" operator and enters the MIN value, it displays and error msg even when the min value is positive and is a number.. I want it to only display the error message on;y after the max value is enter and only if the max value is incorrect.
How can I display the error message Only when both min and max are entered.. incorrectly.
function minmaxval(min, max, op) {
var rVal = "",
msg = "",
errormsg = "Enter a Max Value larger then Min Value and all number should be greater then 0!",
errormsg2 = "Enter a number greater then 0!";
if (operator === "between") {
if (this.getNumber(min) !== false && this.getNumber(max) !== false && (min < max) && (min > 0)) {
displayMessage(min, max, msg);
rVal = "(" + min + " - <span class='truncate'> " + max + "</span>)";
} else {
if((min!="")&&(max!="") &&(min>max)) {
displayMessage(min, max, errormsg);
rVal = "";
}
}
}
return rVal ;
}
displayMessage(min,max,msg) {
document.getElementByID("#err").innerHTML=msg;
)
Within your operator === "between" block, find this:
if (this.getNumber(min) !== false && this.getNumber(max) !== false && (min < max) && (min > 0)) {
...and change it to this:
if ( (this.getNumber(min) && min > 0)
|| (this.getNumber(min) && this.getNumber(max) && min < max)
) {
In your posted code you're requiring both getNumber(min) and getNumber(max) to be true in order for your first condition to execute, instead of displaying an error message. Change that so your first condition will execute if EITHER getNumber(min) is true and min is greater than 0 OR both are true and min is less than max. Be sure to include the parenthesis so the operators are evaluated in the proper order.

Validate number in jquery

I try to check non negative number in jquery.If other then number my function works but for zero and non negative number its doesn't work.Here is my sample fiddle.
Sample Fiddle
Unable to find my mistake.Thanks.
How about DEMO (NOTE: Error messages are OP's own)
$('#txtNumber').keyup(function() {
var val = $(this).val(), error ="";
$('#lblIntegerError').remove();
if (isNaN(val)) error = "Value must be integer value."
else if (parseInt(val,10) != val || val<= 0) error = "Value must be non negative number and greater than zero";
else return true;
$('#txtNumber').after('<label class="Error" id="lblIntegerError"><br/>'+error+'</label>');
return false;
});
This should work:
$('#txtNumber').keyup(function() {
var num = $(this).val();
num = new Number(num);
if( !(num > 0) )
$('#txtNumber').after('<label class="Error" id="lblIntegerError"><br/>Value must be non negative number and greater than zero.</label>');
});
Note: The parseInt() ignores invalid characters if the first character is numeric but the Number() take cares of them also
$('#txtNumber').keyup(function()
{
$('#lblIntegerError').remove();
if (!isNaN(new Number($('#txtNumber').val())))
{
if (parseInt($('#txtNumber').val()) <=0)
{
$('#txtNumber').after('<label class="Error" id="lblIntegerError"><br/>Value must be non negative number and greater than zero.</label>');
return false;
}
}
else
{
$('#txtNumber').after('<label class="Error" id="lblIntegerError"><br/>Value must be integer value.</label>');
return false;
}
});​
if (isNaN($('#txtColumn').val() <= 0))
That's not right..
You need cast the value to an integer since you're checking against an integer
var intVal = parseInt($('#txtColumn').val(), 10); // Or use Number()
if(!isNaN(intVal) || intVal <= 0){
return false;
}

How to check the value given is a positive or negative integer?

Lets say i have the value 10 assigned to a variable;
var values = 10;
and i want to run a specific function if the value is a positive
if(values = +integer){
//do something with positive
} else {
//do something with negative values
}
How would this be achieved?
if (values > 0) {
// Do Something
}
Am I the only one who read this and realized that none of the answers addressed the "integer" part of the question?
The problem
var myInteger = 6;
var myFloat = 6.2;
if( myInteger > 0 )
// Cool, we correctly identified this as a positive integer
if( myFloat > 0 )
// Oh, no! That's not an integer!
The solution
To guarantee that you're dealing with an integer, you want to cast your value to an integer then compare it with itself.
if( parseInt( myInteger ) == myInteger && myInteger > 0 )
// myInteger is an integer AND it's positive
if( parseInt( myFloat ) == myFloat && myFloat > 0 )
// myFloat is NOT an integer, so parseInt(myFloat) != myFloat
Some neat optimizations
As a bonus, there are some shortcuts for converting from a float to an integer in JavaScript. In JavaScript, all bitwise operators (|, ^, &, etc) will cast your number to an integer before operating. I assume this is because 99% of developers don't know the IEEE floating point standard and would get horribly confused when "200 | 2" evaluated to 400(ish). These shortcuts tend to run faster than Math.floor or parseInt, and they take up fewer bytes if you're trying to eke out the smallest possible code:
if( myInteger | 0 == myInteger && myInteger > 0 )
// Woot!
if( myFloat | 0 == myFloat && myFloat > 0 )
// Woot, again!
But wait, there's more!
These bitwise operators are working on 32-bit signed integers. This means the highest bit is the sign bit. By forcing the sign bit to zero your number will remain unchanged only if it was positive. You can use this to check for positiveness AND integerness in a single blow:
// Where 2147483647 = 01111111111111111111111111111111 in binary
if( (myInteger & 2147483647) == myInteger )
// myInteger is BOTH positive and an integer
if( (myFloat & 2147483647) == myFloat )
// Won't happen
* note bit AND operation is wrapped with parenthesis to make it work in chrome (console)
If you have trouble remembering this convoluted number, you can also calculate it before-hand as such:
var specialNumber = ~(1 << 31);
Checking for negatives
Per #Reinsbrain's comment, a similar bitwise hack can be used to check for a negative integer. In a negative number, we do want the left-most bit to be a 1, so by forcing this bit to 1 the number will only remain unchanged if it was negative to begin with:
// Where -2147483648 = 10000000000000000000000000000000 in binary
if( (myInteger | -2147483648) == myInteger )
// myInteger is BOTH negative and an integer
if( (myFloat | -2147483648) == myFloat )
// Won't happen
This special number is even easier to calculate:
var specialNumber = 1 << 31;
Edge cases
As mentioned earlier, since JavaScript bitwise operators convert to 32-bit integers, numbers which don't fit in 32 bits (greater than ~2 billion) will fail
You can fall back to the longer solution for these:
if( parseInt(123456789000) == 123456789000 && 123456789000 > 0 )
However even this solution fails at some point, because parseInt is limited in its accuracy for large numbers. Try the following and see what happens:
parseInt(123123123123123123123); // That's 7 "123"s
On my computer, in Chrome console, this outputs: 123123123123123130000
The reason for this is that parseInt treats the input like a 64-bit IEEE float. This provides only 52 bits for the mantissa, meaning a maximum value of ~4.5e15 before it starts rounding
To just check, this is the fastest way, it seems:
var sign = number > 0 ? 1 : number == 0 ? 0 : -1;
//Is "number": greater than zero? Yes? Return 1 to "sign".
//Otherwise, does "number" equal zero? Yes? Return 0 to "sign".
//Otherwise, return -1 to "sign".
It tells you if the sign is positive (returns 1), or equal to zero (returns 0), and otherwise (returns -1). This is a good solution because 0 is not positive, and it is not negative, but it may be your var.
Failed attempt:
var sign = number > 0 ? 1 : -1;
...will count 0 as a negative integer, which is wrong.
If you're trying to set up conditionals, you can adjust accordingly. Here's are two analogous example of an if/else-if statement:
Example 1:
number = prompt("Pick a number?");
if (number > 0){
alert("Oh baby, your number is so big!");}
else if (number == 0){
alert("Hey, there's nothing there!");}
else{
alert("Wow, that thing's so small it might be negative!");}
Example 2:
number = prompt("Pick a number?");
var sign = number > 0 ? 1 : number == 0 ? 0 : -1;
if (sign == 1){
alert("Oh baby, your number is so big!" + " " + number);}
else if (sign == 0){
alert("Hey, there's nothing there!" + " " + number);}
else if (sign == -1){
alert("Wow, that thing's so small it might be negative!" + " " + number);}
I thought here you wanted to do the action if it is positive.
Then would suggest:
if (Math.sign(number_to_test) === 1) {
function_to_run_when_positive();
}
1 Checking for positive value
In javascript simple comparison like: value >== 0 does not provide us with answer due to existence of -0 and +0
(This is concept has it roots in derivative equations) Bellow example of those values and its properties:
var negativeZero = -0;
var negativeZero = -1 / Number.POSITIVE_INFINITY;
var negativeZero = -Number.MIN_VALUE / Number.POSITIVE_INFINITY;
var positiveZero = 0;
var positiveZero = 1 / Number.POSITIVE_INFINITY;
var positiveZero = Number.MIN_VALUE / Number.POSITIVE_INFINITY;
-0 === +0 // true
1 / -0 // -Infinity
+0 / -0 // NaN
-0 * Number.POSITIVE_INFINITY // NaN
Having that in mind we can write function like bellow to check for sign of given number:
function isPositive (number) {
if ( number > 0 ) {
return true;
}
if (number < 0) {
return false;
}
if ( 1 / number === Number.POSITIVE_INFINITY ) {
return true;
}
return false;
}
2a Checking for number being an Integer (in mathematical sense)
To check that number is an integer we can use bellow function:
function isInteger (number) {
return parseInt(number) === number;
}
//* in ECMA Script 6 use Number.isInteger
2b Checking for number being an Integer (in computer science)
In this case we are checking that number does not have any exponential part (please note that in JS numbers are represented in double-precision floating-point format)
However in javascript it is more usable to check that value is "safe integer" (http://people.mozilla.org/~jorendorff/es6-draft.html#sec-number.max_safe_integer) - to put it simple it means that we can add/substract 1 to "safe integer" and be sure that result will be same as expected from math lessons.
To illustrate what I mean, result of some unsafe operations bellow:
Number.MAX_SAFE_INTEGER + 1 === Number.MAX_SAFE_INTEGER + 2; // true
Number.MAX_SAFE_INTEGER * 2 + 1 === Number.MAX_SAFE_INTEGER * 2 + 4; // true
Ok, so to check that number is safe integer we can use Number.MAX_SAFE_INTEGER / Number.MIN_SAFE_INTEGER and parseInt to ensure that number is integer at all.
function isSafeInteger (number) {
return parseInt(number) === number
&& number <== Number.MAX_SAFE_INTEGER
&& number >== Number.MIN_SAFE_INTEGER
}
//* in ECMA Script 6 use Number.isSafeInteger
simply write:
if(values > 0){
//positive
}
else{
//negative
}
if(values >= 0) {
// as zero is more likely positive than negative
} else {
}
if ( values > 0 ) {
// Yeah, it's positive
}
if ( values > 0 ) {
//you got a positive value
}else{
//you got a negative or zero value
}
To check a number is positive, negative or negative zero. Check its sign using
Math.sign() method it will provide you -1,-0,0 and 1 on the basis of positive negative and negative zero or zero numbers
Math.sign(-3) // -1
Math.sign(3) // 1
Math.sign(-0) // -0
Math.sign(0) // 0
I know it's been some time, but there is a more elegant solution. From the mozilla
docs:
Math.sign(parseInt(-3))
It will give you -1 for negative, 0 for zero and 1 for positive.
You can use the shifting bit operator, but it won't get the difference between -0 and +0 like Math.sign(x) does:
let num = -45;
if(num >> 31 === -1)
alert('Negative number');
else
alert('Positive number');
https://jsfiddle.net/obxptgze/
Positive integer:
if (parseInt(values, 10) > 0) {
}
I use in this case and it works :)
var pos = 0;
var sign = 0;
var zero = 0;
var neg = 0;
for( var i in arr ) {
sign = arr[i] > 0 ? 1 : arr[i] == 0 ? 0 : -1;
if (sign === 0) {
zero++;
} else if (sign === 1 ) {
pos++;
} else {
neg++;
}
}
You should first check if the input value is interger with isNumeric() function. Then add the condition or greater than 0.
This is the jQuery code for it.
function isPositiveInteger(n) {
return ($.isNumeric(n) && (n > 0));
}
For checking positive integer:
var isPositiveInteger = function(n) {
return ($.isNumeric(n)) && (Math.floor(n) == n) && (n > 0);
}
Starting from the base that the received value is a number and not a string, what about use Math.abs()? This JavaScript native function returns the absolute value of a number:
Math.abs(-1) // 1
So you can use it this way:
var a = -1;
if(a == Math.abs(a)){
// false
}
var b = 1;
if(b == Math.abs(b)){
// true
}
The Math.sign() function returns either a positive or negative +/- 1, indicating the sign of a number passed into the argument. If the number passed into Math.sign() is 0, it will return a +/- 0. Note that if the number is positive, an explicit (+) will not be returned.
console.log(Math.sign(-3));
let num = -123;
let val = Math.sign(num);
if(val === -1){
console.log(num + " is negative number");
}else{
console.log(num + " is posative number");
}

Categories