How to compare Negative numbers in javascript - javascript

I want to compare validation range in between -180 to 180 .
If number is less than -180 and greater than 180 then it should show error.
I have written below code for this -
if((markerPoint[0] && parseInt(markerPoint[0],10) < -180 || parseInt(markerPoint[0],10) > 180)) {
this.latlngError.push("Invalid coordinates");
} else {
this.isLanLngValid = true;
}
But this is returning incorrect comparison.

I want to compare validation range in between -180 to 180
For number between -180 and 180 the number must be greater then -180 and less then 180, so change the comparison.
if(markerPoint[0] && parseInt(markerPoint[0],10) > -180 && parseInt(markerPoint[0],10) < 180) {

try this JsFiddle
var answer = prompt("type a number");
func();
function func() {
if (answer>=-180&&answer<=180) {
alert("Yes! We made it!");
} else {
answer = prompt("Invalid try agian");
func();
}
}

Replace below code it will work for sure.
if(markerPoint[0]>=-180 && markerPoint[0]<=180)

One problem with your code is that in JavaScript && has higher precedence than ||. (See the table here.) Thus, the logic is evaluated as if it were parenthesized:
if (
(markerPoint[0] && parseInt(markerPoint[0],10) < -180)
||
parseInt(markerPoint[0],10) > 180)
{
You can use parentheses to change that:
if(markerPoint[0] && (parseInt(markerPoint[0],10) < -180 || parseInt(markerPoint[0],10) > 180)) {
Then the if test will pass if markerPoint[0] is a truthy value and if it evaluates to something outside the range [-180, 180].

You can use Math.abs() instead:
if (markerPoint[0] && Math.abs(parseInt(markerPoint[0],10)) > 180)
Edit: As noted by #TedHopp, the visible issue with your current code seems to be operator precedence. && has higher precedence than ||. Using Math.abs() bypasses the issue.
If that doesn't solve the problem, then more code needs to be supplied for debugging.

Related

Verbose javascript conditional seeks simplification

I have the following rather verbose conditional, I'm trying to wrap my head around a simpler version but I'm not getting anywhere.
if( agent % $.settings.gridSize === 0 && value % $.settings.gridSize == 1 ){
// Dud
}else if(agent % $.settings.gridSize == 1 && value % $.settings.gridSize === 0){
// Dud
}else{
freeCells.push(value);
}
Is there a way I can achieve the same condition with a single if statement, rather than using the throw-away if else?
Something like:
if(!(a && b) && !(x && y)){
// Do stuff
}
Yes, it's possible and you've (almost) answered your question yourself.
You can do the following:
var gS = $.settings.gridSize;
if(!(agent % gS === 0 && value % gS == 1) && !(agent % gS == 1 && value % gS === 0)) {
freeCells.push(value);
}
Depending on the possible values of $.settings.gridSize etc., it's possible that what you are looking for is:
if (agent % $.settings.gridSize !== value % $.settings.gridSize) {
// Dud
} else {
which also makes the semantics clearer: the modulo involving agent should be "different" (in the 0/1 sense) from the module involving value.
if (
agent % $.settings.gridSize > 1
||
(agent + value) % $.settings.gridSize !== 1
) {
freeCells.push(value);
}
I think it's pretty self-explaining.
Edit
Seems like it isn't that self-explaining actually.
I made a few assumptions for the transformation.
// Dud means to do nothing.
$.settings.gridSize is a positive integer, henceforth referred to as gridSize.
agent and value are non-negative integers.
For a value not to be pushed agent % gridSize has to be either 0 or 1. Since there are no negative numbers or fractional parts involved this means the same as agent % gridSize <= 1. So if the remainder is greater than 1 then value gets pushed.
Otherwise agent % gridSize is either 0 or 1. And for the value not to be pushed value % gridSize has to take on the respective other value. In total this would mean that (agent + value) % gridSize === 1. So if it's not 1 then value gets pushed.

javascript window.innerWidth conditional statement

I have a script which shows different content depending on the screen size, it looks like this:
if ((window.innerWidth < 1250 )) {
//Do something
}
I am trying to set a greater than value as well as a less than value. I thought the follwoing would work:
if ((window.innerWidth < 1250 && > 750)) {
//Do something
}
Can anyone help me out?
When using Boolean operators (&&, ||, etc), each side must be a completely valid Boolean expression on its own. && > 750 is not a valid expression, since > 750 cannot be evaluated as True or False.
What you want is :
if (window.innerWidth < 1250 && window.innerWidth > 750) {
As both window.innerWidth < 1250 and window.innerWidth > 750 are valid expressions and can be resolved independently.
Close:
if (window.innerWidth < 1250 && window.innerWidth > 750) {
You need to repeat the comparison argument after the && to check with new value.
Use like this:
if (window.innerWidth < 1250 && window.innerWidth > 750) {
function between(val, min, max)
{
return val >= min && val <= max;
}
if (between(window.innerWidth,750,1250)) {
//your code!!!
}

JavaScript Conditional Statement Not Working

What's wrong with this JavaScript?
var numPackages == 0;
if (coffeeProducts <= 12) {
numPackages == 1;
} else if (coffeeProducts % 12 == 0) {
numPackages == coffeeProducts/12;
} else {
numPackages == (coffeeProducts/12) + 1;
}
Basically, it needs to calculate the number of boxes/packages necessary to ship an amount of items (12 per box). Is there a better way to do this, perhaps using round()?
== is condition.
= is assignment.
The better way is to use Math.ceil() to round to next integer.
So:
var numPackages = Math.ceil(coffeeProducts/12);
All the others explained your mistake with the comparing operator == and the assigning operator =.
The shortest way to solve it would be
var numPackages = Math.ceil( coffeeProducts / 12 );
Make each statement look like this:
if (coffeeProducts <= 12) {
numPackages = 1; // just "=", not "=="
}
Single equals (=) for assignment: x = 10
Double equals (==) for comparison: if (x == 10)
Triple equals for special cases where type is important as well as the value.
Change your two numPackages lines to a single equals and you're good to go :)

Javascript Finding Prime Numbers

I am writing a little script to find and print out all the prime numbers from X thru Y. Here is what I have written:
var numX = prompt('Enter a number greater than 0:','');
var numY = prompt('Enter a number greater than ' + numX + ':','');
while (numX <= numY) {
if (numX == 1 || numX == 2 || numX == 3) {
document.write(numX + '</br>');
} else if (numX % 2 === 0 || numX % 3 === 0 || numX % 5 === 0 || numX % 7 === 0){
document.write();
} else {
document.write(numX + '</br>');
}
numX++;
};
Now, this works just fine so long as the first number is 1. If, however, the first number is anything greater than 1 it does not print out anything. I am not sure if this is the right forum for this question (perhaps a math forum?), but I thought I would ask here on the off chance someone could help me out. I also know that a sieve is the better way to go about this, but I wanted to try and figure this out as a while loop first. Any and all help is appreciated!
While I understand what you are trying to do, I highly recommend taking a look at the Sieve of Eratosthenes. You really want to get the hang of knowing different algorithms to compute these things in case you decide to deal with really large numbers. While the way you go about it now might work in smaller ranges, bigger ranges are going to go crazy.
Also I believe this Stackoverflow question is very similar to this one and the answer for it is very well made:
finding sum of prime numbers under 250
You can try any of the options here : http://www.javascripter.net/faq/numberisprime.htm
Hi i have added bit change to ur code (added condition for 5 and 7 prime numbers) and its working...
var numX = prompt('Enter a number greater than 0:','');
var numY = prompt('Enter a number greater than ' + numX + ':','');
while (numX <= numY) {
if (numX == 1 || numX == 2 || numX == 3 || numX == 5 || numX == 7) {
document.write(numX + '</br>');
} else if (numX % 2 === 0 || numX % 3 === 0 || numX % 5 === 0 || numX % 7 === 0){
document.write();
} else {
document.write(numX + '</br>');
}
numX++;
};
Check the demo here
OK, turns out that I jumped the gun on asking this question. I was more concerned with getting the else if statement working that I failed to even note that my formula was seriously flawed!
The issue possibly could be with the second variable. If the first variable is 1 then the second variable can be any number. However, if the first variable is greater than 1 then the second variable has to be less than 100 or it will not work.

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