Javascript Greater than or less than - javascript

I did a rewrite of the code I submitted yesterday based on suggestions from others. I now have this but still can't seem to get it to work with greater than less than. I can add/substract the 2 numbers and get a valid answers. I can't get a > < to work however. Hoping someone can offer some additional help keeping it within this format of "If statements".
if ((input.search("what is greater")!= -1) && (input.search(/\d{1,10}/)!=-1) && (input.search(/\d{1,10}/)!=-1))
{var numbersInString = input.match(/\d+/g);
var num1 = parseInt( numbersInString[0], 10 );
var num2 = parseInt( numbersInString[1], 10 );
if (num1 < num2) document.result.result.value = ""+num1+" is less than "+num2+"";
if (num1 > num2) document.result.result.value = ""+num1+" is greater than "+num2+"";
if (num1 = num2) document.result.result.value = "Both numbers are equal";
return true;}

It sounds like you want to manipulate a number in two ways:
1) You want to refer to the individual characters.
2) You want to compare the number to another number and see if one is greater than another.
If you have a string called input, then you can use the function parseInt(input, 10) to convert it from a string to the number represented by that string.
If you want to get just the first two characters, you can use the substring function.
The important thing to keep in mind is that to the computer, the string '12345' and the number 12345 are completely different. The computer has a completely different set of operations that it will perform on each.
also, #albin is correct to point out that putting semicolons after your if statements is wrong.

The output of the match method is an array of strings, so I think you are NOT comparing numbers but strings. Try doing this before comparing your numbers.
var num1 = parseInt( numbersInString[0], 10 );
var num2 = parseInt( numbersInString[1], 10 );
And then compare num1 and num2.

http://jsfiddle.net/qt3RW/
Simple input box:
​​​​
<input id="input1" value="Is 6 greater than 5"></input>
Parser find 'Is # greater than #' where # is digit and alert this digits:
var IsStringValid = $("#input1").val().match(/Is \d greater than \d/g);
alert(IsStringValid);
if(IsStringValid){
var values = $("#input1").val().match(/\d/g);
for(var i = 0; i < values.length; i++){
alert(values[i])
}
}
​

Related

Extending a Variable's Length With Random Numbers Doesn't Work

I am making an AI that tries to solve a user-inputted "numberle" in JavaScript. I don't want the user to do extra work just to see an AI do it's thing, so on the input field, if the user inputs a number that has less than 5 digits, the JavaScript should add random numbers at the end of the variable, until it has a total of five digits.
I used all the loops I had experience with, under an if statement, so if the length of the input was less than 5 (like 3), the loop will add 5 - the number of digits of the input (2) digits that are random, using the Math.random attribute.
Here is the code I currently have:
if (input.length < 5)
do {
input = (input * 10) + Math.floor(Math.random() * 9) + 1;
} while (input.length < 5);
}
console.log(input)
I have also used the for and while loops with basically the same condition (obviously modified for the if loop; made a variable for input.length so that it has the same value).
Here is what I get in the console:
5 // Inputted number (1 digit)
52 // Inputted digit + random number
As you can see, the loop only runs once, although it should've ran 3 more times. I am using strict mode also. My code editor is github.dev, and I am using the CodeSwing console.
If input is a number, it will not have "length", since it is not a string.
You can achieve the desired result like this:
let input = 5;
let digits = 2;
while (input < 10**(digits-1)) input = ~~((input+Math.random())*10);
console.log(input);
Note that ~~ is a compact way of doing Math.floor()
Alternatively, without a while loop:
let input = 5, digits = 2, M = Math; L = x=>~~(M.log(x)/M.log(10))+1;
input = ~~((input+M.random())*10**(digits - L(input)));
console.log(input);

Addition and Subtraction with Negative Numbers

I tried adding and subtracting negative numbers with this code
var num1 = parseInt(document.form1.num1.value);
var num2 = parseInt(document.form1.num2.value);
if(operand == "plus"){
var sum = parseInt(num1+num2);
// add alerts to check
alert (num1);
alert (num2);
alert (sum);
}else{
var sum = parseInt(num1-num2);
}
but when I print the result (sum), the program ignore the negative number and just count it as if it's a positive number. I tried delete the parseInt but nothing changes.
for those who's confused : my inputs are num1 and num2. using the code I had, if I input (4) and (-2) and choose plus sign, sum = 6. they dont count the negative as negative, but as positive.
update : apparently even if I input (-2), they save it as (2).
Assuming sum1 and sum2 are string literals, what you should do is parseInt(num1) + parseInt(num2)
It seems your problem is that you're applying a double negative, which makes a positive:
4 - -2 == 4 + 2

JavaScript IF statement evaluating TRUE incorrectly - why?

I have a very, very simple logical test of the number of licenses a customer has purchased vs. the number they have used:
else if(utype == "3"){
var tech_lic = $("#technician_lic").val();
console.log('tech lic = ' + tech_lic)
var tech_allow = $("#technician_lic_allow").val();
console.log('tech allow = ' + tech_allow)
if(tech_lic >= tech_allow)
{
alert("You must purchase more licenses to create this Technician");
return false;
}
I threw in the console.log statements trying to debug this - normally they aren't there.
Console.log when I click "add" button:
tech lic = 4 application.js:262
tech allow = 100 application.js:264
Then we hit "You must purchase more licenses" alert in the window.
WHAT THE HECK?
How can 4 >= 100 evaluate true?
Because .val returns a string. '4' is indeed greater than or equal to '100'. Cast the values to numbers first (if you know that they are always numbers for the purposes of this comparison).
if (+tech_lic >= +tech_allow)
You are evaluating them as strings, so "4" IS greater than "100".
You will need to cast them as integers before comparison:
var tech_lic = parseInt($("#technician_lic").val(), 10);
var tech_allow = parseInt($("#technician_lic_allow").val(), 10);
The string "4" is greater than "100", whereas the number 4 is less than 100.
It's not that 4 >= 100 is true, it's that "4" >= "100" is true.
The values that you get are strings, so they will be compared lexically, not numerically.
Parse the values into numbers:
var tech_lic = parseInt($("#technician_lic").val(), 10);
var tech_allow = parseInt($("#technician_lic_allow").val(), 10);
Do this way:-
if(Number(tech_lic) >= Number(tech_allow))
{
// Do your stuff
}

How to increment a numeric string by +1 with Javascript/jQuery

I have the following variable:
pageID = 7
I'd like to increment this number on a link:
$('#arrowRight').attr('href', 'page.html?='+pageID);
So this outputs 7, I'd like to append the link to say 8. But if I add +1:
$('#arrowRight').attr('href', 'page.html?='+pageID+1);
I get the following output: 1.html?=71 instead of 8.
How can I increment this number to be pageID+1?
Try this:
parseInt(pageID, 10) + 1
Accordint to your code:
$('#arrowRight').attr('href', 'page.html?='+ (parseInt(pageID, 10) + 1));
+ happens to be valid operator for both strings and numbers that gives different results when both arguments are numeric and when at least one is not. One of possible workarounds is to use operator that only have numeric context but gives same mathematical result, like -. some_var - -1 will always be same as adding 1 to some_var's numeric value, no matter if it is string or not.
$('#arrowRight').attr('href', 'page.html?='+ (pageID - -1));
All these solutions assume that your number you want to add 1 to is within the machine precision for an integer. So if you have a large enough number within that string when you add 1 to it won't change the number.
For Example:
parseInt('800000000000000000', 10) + 1 = 800000000000000000
So I wrote a quick solution to the problem
function addOne(s) {
let newNumber = '';
let continueAdding = true;
for (let i = s.length - 1; i>= 0; i--) {
if (continueAdding) {
let num = parseInt(s[i], 10) + 1;
if (num < 10) {
newNumber += num;
continueAdding = false;
} else {
newNumber += '0';
}
} else {
newNumber +=s[i];
}
}
return newNumber.split("").reverse().join("");
}
Now, using the same example above
addOne('800000000000000000') + 1 = '800000000000000001'
Note that it must stay as a string or you will lose that 1 at the end.
It needs to be a integer, not a string. Try this:
pageID = parseInt(pageID)+1;
Then you can do
$('#arrowRight').attr('href', 'page.html?='+pageID);
Simply, $('#arrowRight').attr('href', 'page.html?='+(pageID+1));
The parentheses makes the calculation done first before string concatenation.
let pageId = '7'
pageId++
console.log(pageId)
Nowadays, you just need to pageID++.
Just change your order of operations by wrapping your addition in parentheses; if pageID is already a number, parseInt() isn't necessary:
$('#arrowRight').attr('href', 'page.html?='+(pageID+1));
Demo
As long as your pageID is numeric, this should be sufficient:
$('#arrowRight').attr('href', 'page.html?='+(pageID+1));
The problem you were seeing is that JavaScript normally executes in left-to-right order, so the string on the left causes the + to be seen as a concatenator, so it adds the 7 to the string, and then adds 1 to the string including 7.

Detect if a number is between 2 others?

What's the best way to detect if a number, is between two other numbers? Is there already a function to do this in the Math object?
There is no specific function, but you can do it like this:
lowNumber < yourNumber && yourNumber < highNumber
Though the code solution is fairly obvious, if you're going to use it a lot, you may want to implement it on Number.prototype for convenience:
Number.prototype.inRange = function( a,b ) {
var n = +this;
return ( n > a && n < b );
};
So you'd use it like this:
(5).inRange( 3, 7 ); // true
Example: http://jsfiddle.net/dTHQ3/
Um if it is greater than one and less than the other.
var num1 = 3;
var num2 = 5;
var x = 4;
var isBetween = (num1 < x && num2 > x);
if ( yournumber < highNumber && yournumber > lowNumber ){
// do something
} else {
// do something else
}
The only optimized way to do this is to guess which is more likely: Is the number your checking more likely to be lower than the lower bound, or is it more likely to be higher than the upper bound?
With this in mind, you can take advantage of short circuiting by placing the more likely failure check first (if it fails that, it won't test the less likely criteria). This is the only way to optimize it.
Even this will save you the smallest amount of time that is most likely not going to be noticed. Perhaps if you were making this check millions of times, you might save a fraction of a second over the alternative.

Categories

Resources