Comparing negative numbers in JQuery function - javascript

I am trying to compare two negative numbers and the comparison is failing. In this specific case, getLeftPercent() is a negative number (-14) yet when comparing, action B is performed. Logically, (-14) is less than (-10) thus action A should be performed.
If I change the right side comparison operand (-10) to a positive number (1 for example) then action A is performed. Is there some quirk of JavaScript that I'm overlooking (which is staring me in the face)? I can post the complete code but there's not really much more.
$(function() {
// the statement in question
if (parseInt(getLeftPercent(), 10) < -10) {
// do action A
// this is just a debug statement
$('#posbanner').html('element position is less than negative 10');
} else {
// do action B
// this is just a debug statement
$('#posbanner').html('element position is greater than or equal to negative 10');
}
});
// element left position on page
function getLeftPercent() {
var leftStr = $('#sidebar').css('left'),
pxPos = leftStr.indexOf('px'),
leftVal = leftStr.substr(0, pxPos),
leftPercent = (leftVal / $(window).width() * 100).toString(),
dotPos = leftPercent.indexOf('.'),
leftPercentStr = dotPos == -1 ? leftPercent : leftPercent.substr(0, dotPos);
return leftPercentStr;
};

I tried running the following code on jsfiddle
if (parseInt( -14, 10) < -10)
{
alert("I am in A");
}
else
{
alert("I am in B");
}
I get I am in A
Not sure, if getLeftPercent() is returning the value you expect.

Your getLeftPercent() function seems way overcomplicated. I'm not sure whether your "left" is relative to the document or parent element, I'll assume document here.
function getLeftPercent() {
'use strict';
return ( ($('#sidebar').offset()).left * 100 / $(window).width() );
}

Most likely your substrings return some characters before the number.
alert(parseInt('-14abc', 10)); // -14
alert(parseInt('abc-14', 10)); // NaN

Related

Javascript Help - selfDividingNumbers Algorithm producing all 0's

Greetings Stack Overflow!
First off, this is my first question!
I am trying to solve the selfDividingNumbers algorithm and I ran into this interesting problem. This function is supposed to take a range of numbers to check if they are self dividing.
Self Dividing example:
128 is a self-dividing number because
128 % 1 == 0, 128 % 2 == 0, and 128 % 8 == 0.
My attempt with Javascript.
/*
selfDividingNumbers( 1, 22 );
*/
var selfDividingNumbers = function(left, right) {
var output = [];
while(left <= right){
// convert number into an array of strings, size 1
var leftString = left.toString().split();
// initialize digit iterator
var currentDigit = leftString[0];
for(var i = 0; i < leftString.length; i++){
currentDigit = parseInt(leftString[i])
console.log( left % currentDigit );
}
// increment lower bound
left++;
}
return output
};
When comparing the current lower bound to the current digit of the lower bound, left % currentDigit it always produces zero! I figure this is probably a type error but I am unsure of why and would love for someone to point out why!
Would also like to see any other ideas to avoid this problem!
I figured this was a good chance to get a better handle on Javascript considering I am clueless as to why my program is producing this output. Any help would be appreciated! :)
Thanks Stack Overflow!
Calling split() isn't buying you anything. Remove it and you'll get the results you expect. You still have to write the code to populate output though.
The answer by #Joseph may fix your current code, but I think there is a potentially easier way to go about doing this. Consider the following script:
var start = 128;
var num = start;
var sd = true;
while (num > 0) {
var last = num % 10;
if (start % last != 0) {
sd = false;
break;
}
num = Math.floor(num / 10);
}
if (sd) {
print("Is self dividing");
}
else {
print("Is NOT self dividing");
}
Demo
To test each digit in the number for its ability to cleanly divide the original number, you can simply use a loop. In each iteration, check num % 10 to get the current digit, and then divide the number by ten. If we never see a digit which can not divide evenly, then the number is not self dividing, otherwise it is.
So the string split method takes the string and returns an array of string parts. The method expects a parameter, however, the dividing element. If no dividing element is provided, the method will return only one part, the string itself. In your case, what you probably intended was to split the string into individual characters, which would mean the divider would be the empty string:
var leftString = left.toString().split('');
Since you are already familiar with console.log, note that you could also use it to debug your program. If you are confused about the output of left % currentDigit, one thing you could try is logging the variables just before the call,
console.log(typeof left, left, typeof currentDigit, currentDigit)
which might give you ideas about where to look next.

Javascript: parsing negative Number(hexadecimal | binary)

It works with a lot number types, but not with negatives hexadecimal or binary.
Too, Number(octal) doesn't parse an octal number.
Number("15") === 15; // OK
Number("-15") === -15; // OK
Number("0x10") === 16; // OK
Number("0b10") === 2; // OK
Number("-0x10") === NaN; // FAIL (expect -16)
Number("-0b10") === NaN; // FAIL (expect -2)
Number("0777") === 777; // FAIL (expect 511)
Number("-0777") === -777; // FAIL (expect -511)
Question: how I can parse all valid Javascript numbers correctly?
Edit A
parseInt() don't help me because I need check by each possibility (if start with 0x I use 16, for instance).
Edit B
If I write on Chrome console 0777 it turns to 511, and too allow negative values. Even works if I write directly into javascript code. So I expect basically a parser that works like javascript parser. But I think that the negative hexadecimal, for instance, on really is 0 - Number(hex) in the parser, and not literraly Number(-hex). But octal values make not sense.
Try this:
parseInt(string, base):
parseInt("-0777", 8)
parseInt("-0x10", 16)
You could write a function to handle the negative value.
function parseNumber (num) {
var neg = num.search('-') > -1;
var num = Number(num.replace('-', ''));
return num * (neg ? -1 : 1);
}
It's not parsing octal and the other examples because they're not valid Javascript numbers, at least within the constraints of Number. So the technically correct answer is: use Number!
If you want to parse other formats, then you can use parseInt, but you will have to provide the base.
This gets a little ugly, but you could inspect the values to determine the right radix for parseInt. In particular, the b for binary doesn't seem to be support by my browser (Chrome) at all, so unlike the OP, Number("0b10") gives me NaN. So you need to remove the b for it to work at all.
var numbers = [
"15", "-15", "0x10", "0b10", "-0x10", "-0b10", "0777", "-0777"
];
function parser(val) {
if (val.indexOf("x") > 0) {
// if we see an x we assume it's hex
return parseInt(val, 16);
} else if (val.indexOf("b") > 0) {
// if we see a b we assume it's binary
return parseInt(val.replace("b",""),2);
} else if (val[0] === "0") {
// if it has a leading 0, assume it's octal
return parseInt(val, 8);
}
// anything else, we assume is decimal
return parseInt(val, 10);
}
for (var i = 0; i < numbers.length; i++) {
console.log(parser(numbers[i]));
}
Note this obviously isn't foolproof (for example, I'm checking for x but not X), but you can make it more robust if you need to.

Replace modulus by function

When I try to do 8067 % 80.67 I get 80.66999999999983, instead of 0 beacuse of known floating point javascript behaviour.
So I went and made a function for this, to avoid floating point javascript errors.
function math(a, b) {
var left = Math.abs(a),
times = 1,
abs = a >= 0 ? 1 : -1;
while (Math.abs(a) >= b * times) {
left -= b;
times++;
}
return (a - (b * (times - 1))) * abs;
}
http://jsfiddle.net/s5w3C/
So my question is: is this usefull, ie a good tool to use instead of %? is there cases where this will also give falsy results like the modulus % oprator.
I am looking for a tools to calculate % consistently.
I didn't really inspect the algorithm for correctness, but if you care about efficiency, this is a bad idea. Basically, the larger the input, the slower your code will execute.
I think any fix will only work to a certain level of accuracy and for certain sized numbers. Perhaps something like the following will be sufficient:
function nearlyMod(a, b) {
var precision = ('' + b).split('.').length;
var estimate = (a % b).toFixed(precision);
return estimate == b ? 0 : +estimate;
}
console.log(nearlyMod(8067, 80.66)); // 1
console.log(nearlyMod(8067, 80.67)); // 0
console.log(nearlyMod(8067, 80.68)); // 79.68
It tests if the result is an even divisor within the precision of the original number. If so, it returns 0, otherwise it returns a number to the same precision (which may or may not be what you want).
The result is always a number (the value returned from toFixed is a string, hence +estimate).
A better name might be "roundedMod" or similar.

if number is between two numbers by plus/minus 10 addclass

http://jsfiddle.net/kM8xE/2/
If I have the divs
​
<div class="value">15</div>
<div class="value2">20</div>​
and jQuery
var actual = $(".value").html();
var comparison = $(".value2").html();
how can i add class .isbetween to .value2 if it's html value is between +/-10 of the html for .value ie. for this eg. a value between 5 and 25.
I am not too good but i have tried and it doesn't work.
if(parseInt(actual)-10 <= parseInt(comparison) <= parseInt(actual)+10){
$(".value2").addClass("isbetween");
}
if (Math.abs(actual - comparison) <= 10) {
//they're within 10
}
The reason this doesn't work is that you can't chain comparisons like this:
5 < x < 10
In Javascript (and other languages with c-like syntax), you have to make two separate comparisons, and use the boolean and operator (&&) to chain the comparisons together:
var actualValue = parseInt(actual);
var comparisonValue = parseInt(comparison);
if(actualValue - 10 <= comparisonValue && comparisonValue <= actualValue + 10) {
$(".value2").addClass("isbetween");
}
Also, don't repeat yourself. Do the conversion once, and store it in a local variable. This makes the code much more readable.
This can be made even more simple by using a concept called absolute value. Then you can just do your difference, and see if its absolute value is less than or equal to ten.
var delta = Math.abs(parseInt(actual) - parseInt(comparison));
if(delta <= 10) {
$(".value2").addClass("isbetween");
}
You have to get the two values, convert them to numbers, compare the absolute value of their difference and then add the class if it meets your condition:
var v1 = +$(".value").text();
var v2 = +$(".value2").text();
if (Math.abs(v1 - v2) <= 10) {
$(".value2").addClass("isbetween");
}

Best way to prevent/handle divide by 0 in javascript

What is the best way to prevent divide by 0 in javascript that is accepting user inputs.
If there is no particular way to achieve this what would be the best way to handle such a situation so as to not prevent other scripts from executing?
Any insights are much appreciated.
There is no way to do that with the normal / and /= operators.
The best way to do what you want is with guards:
function notZero(n) {
n = +n; // Coerce to number.
if (!n) { // Matches +0, -0, NaN
throw new Error('Invalid dividend ' + n);
}
return n;
}
and then do division like
numerator / notZero(denominator)
Alternatively you can always guard the output
function dividend(numerator, denominator) {
var quotient = numerator / denominator;
if (quotient !== quotient) { throw new Error(numerator + " / " + denominator); }
return quotient;
}
but that loses the readability and expressiveness of /=.
Off the top of my head you could:
Check the user input to see if the denominator is zero (or evaluates to zero, depending on what your script actually does).
Check if the result of the action isFinite() and if not then handle appropriately.
what would be the best way to handle such a situation so as to not prevent other scripts from executing
Division by zero doesn't seem to prevent other scripts from execution in JavaScript:
var a = 20;
var b = 0;
var result = a/b;
console.log(result); // returns Infinity
If you want something different to happen in case of division by zero, you could use
function divideIfNotZero(numerator, denominator) {
if (denominator === 0 || isNaN(denominator)) {
return null;
}
else {
return numerator / denominator;
}
}
Hope this is useful
(denominator != 0 ? numerator/denominator : Infinity)
or whatever value you want to put at the end.
Greetings.
To prevent (unwanted) execution
Always verify critical user input and/or results
Use logic and/or callbacks you can prevent to execute
On HTML forms etc. you can use i.e. return false; as value to stop submission.
Why not just check if the denominator is zero?
if(x != 0) z = y / x;
You can also check if the result is Infinity:
3 / 0 == Infinity
Results in true;
(Only tested in chrome.)
A bit different than stopping execution, but the ternary operator is a pretty slick way to customize variable assignment.
var one = 1,
zero = 0,
customValue = 1;
var quotient = zero===0 ? customValue : one / zero;
This way, by setting the customVariable to the integer of your choice, you can expect a predictable result when division by zero occurs.
The best way is contextual. But here's the easiest:
function myFunction( input ){
input = 0 ? 0.0001 : input; // same as if( input == 0 ){ input = 0.0001; }
return 1 / input;
}
Basically if the input is zero, turn it into a very small number before using as a denominator. Works great for integers, since after your division you can round them back down.
A couple caveats prevent this from being universal:
It could cause false positives if your input accepts really small numbers
It won't trigger any error-handling code, if you need to do something special if zero is entered
So it's best for general-purpose, non-critical cases. For example, if you need to return the result of a complex calculation and don't care if the answer is accurate to N digits (determined by 0.0001 vs. 0.00000001, etc.); you just don't want it to break on a divide-by-zero.
As another answer suggested, you could also create a reusable global function.
function divisor( n ){ return ( n = 0 ? 0.0001 : n ); }
function myFunction( input ){ return 1 / divisor( input ); }
Possible improvements:
function divisor( n, orError ){
if( typeof n == 'undefined' || isNaN( n ) || !n ){
if( orError ){ throw new Error( 'Divide by zero.' ); }
return 0.000000000000001;
}else{ return 0 + n; }
}
This would take any value (null, number, string, object) and if invalid or zero, return the failsafe zero-like value. It would also coerce the output to a number just in case it was a string and you were doing something odd. All this would ensure that your divisor function always worked. Finally, for cases where you wanted to handle such errors yourself, you could set the second parameter to true and use a try/catch.
Set a cap on what the value for the numerator can be and set the numerator to that value when the denominator equals 0.
This is a faster approach yet is confusing
let divisor;
let dividend;
let result =(dividend/divisor) || 0
if the result for instance if you are calculating percentage is infinite you can give it 0 as value;
const progress = goal == 0 ? 0 : total/goal

Categories