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
}
Related
Javascript Code
I am concacting two variables and comparing with a string
Why the alert is true? Why it is not coercing??
var str1 = "2";
var str2 = "3";
var res = str1 + str2 // return 23
console.log(res) // 23
console.log("100") // 100
alert(res > "100") // alerts true instead of false
The value in res is a string. In strings "23" is greater than "100" (looking at the first character).
To further answer your question "why isn't javascript coercing" I'd like to quote a comment from James Thorpe
"Both sides are strings - there is nothing to coerce"
Here's a code example.
console.log (23 > "100") // false
console.log ("23" > "100") // true
First console.log compares number with string - javascript coerces.
Second console.log compares string with string - nothing to coerce
Alert is true because '23' is lexicographically greater than '100' ('2' > '1').
You can use parseInt to convert strings to numbers:
alert(parseInt(res) > 100);
Because you are comparing strings. "100" is lower then "23" because "1"<"2".
You should parse to int if you want numerical comparison, as shown in #jh314 answer.
You can temporarily change the string to their number representation i.e, 23 and 100 and use the comparison operator. Either prefix the values with + to change them to numeric value or use parseInt():
var str1 = "2";
var str2 = "3";
var res = str1 + str2 // return 23
console.log(res) // 23
console.log("100") // 100
alert(+res > +"100")
The value of res is "23" not 23. That means it's a string and therefore when you alert the comparison it compares the first digit of each, 2 > 1 which is true.
As for “why is it not coercing?” - because both operands are strings in both cases, and because both + and > are valid operations on strings.
(Using - (subtract) would cause implicit coercion to number because it doesn’t make sense for strings, but concatenation and addition use the same operator. Welcome to JavaScript!)
Your alert is comparing a string and a string.
Try: alert(res > 100)
I have an object property that may or may not contain a number and that number may or may not be equal to 0. For the moment, I have this:
var TheVar = parseInt(SomeObject.SomeVar, 10);
if (!TheVar > 0) {
TheVar = "-";
}
I want TheVar to be either a positive number or "-". I'm just wondering if my conditional statement is going to cover every case?
Thanks for your suggestions.
No. You are missing parentheses.
if( !(TheVar > 0))
NaN > 0 returns false, so the if condition will go through.
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.
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])
}
}
I store some parameters client-side in HTML and then need to compare them as integers. Unfortunately I have come across a serious bug that I cannot explain. The bug seems to be that my JS reads parameters as strings rather than integers, causing my integer comparisons to fail.
I have generated a small example of the error, which I also can't explain. The following returns 'true' when run:
console.log("2" > "10")
Parse the string into an integer using parseInt:
javascript:alert(parseInt("2", 10)>parseInt("10", 10))
Checking that strings are integers is separate to comparing if one is greater or lesser than another. You should always compare number with number and string with string as the algorithm for dealing with mixed types not easy to remember.
'00100' < '1' // true
as they are both strings so only the first zero of '00100' is compared to '1' and because it's charCode is lower, it evaluates as lower.
However:
'00100' < 1 // false
as the RHS is a number, the LHS is converted to number before the comparision.
A simple integer check is:
function isInt(n) {
return /^[+-]?\d+$/.test(n);
}
It doesn't matter if n is a number or integer, it will be converted to a string before the test.
If you really care about performance, then:
var isInt = (function() {
var re = /^[+-]?\d+$/;
return function(n) {
return re.test(n);
}
}());
Noting that numbers like 1.0 will return false. If you want to count such numbers as integers too, then:
var isInt = (function() {
var re = /^[+-]?\d+$/;
var re2 = /\.0+$/;
return function(n) {
return re.test((''+ n).replace(re2,''));
}
}());
Once that test is passed, converting to number for comparison can use a number of methods. I don't like parseInt() because it will truncate floats to make them look like ints, so all the following will be "equal":
parseInt(2.9) == parseInt('002',10) == parseInt('2wewe')
and so on.
Once numbers are tested as integers, you can use the unary + operator to convert them to numbers in the comparision:
if (isInt(a) && isInt(b)) {
if (+a < +b) {
// a and b are integers and a is less than b
}
}
Other methods are:
Number(a); // liked by some because it's clear what is happening
a * 1 // Not really obvious but it works, I don't like it
Comparing Numbers to String Equivalents Without Using parseInt
console.log(Number('2') > Number('10'));
console.log( ('2'/1) > ('10'/1) );
var item = { id: 998 }, id = '998';
var isEqual = (item.id.toString() === id.toString());
isEqual;
use parseInt and compare like below:
javascript:alert(parseInt("2")>parseInt("10"))
Always remember when we compare two strings.
the comparison happens on chacracter basis.
so '2' > '12' is true because the comparison will happen as
'2' > '1' and in alphabetical way '2' is always greater than '1' as unicode.
SO it will comeout true.
I hope this helps.
You can use Number() function also since it converts the object argument to a number that represents the object's value.
Eg: javascript:alert( Number("2") > Number("10"))
+ operator will coerce the string to a number.
console.log( +"2" > +"10" )
The answer is simple. Just divide string by 1.
Examples:
"2" > "10" - true
but
"2"/1 > "10"/1 - false
Also you can check if string value really is number:
!isNaN("1"/1) - true (number)
!isNaN("1a"/1) - false (string)
!isNaN("01"/1) - true (number)
!isNaN(" 1"/1) - true (number)
!isNaN(" 1abc"/1) - false (string)
But
!isNaN(""/1) - true (but string)
Solution
number !== "" && !isNaN(number/1)
The alert() wants to display a string, so it will interpret "2">"10" as a string.
Use the following:
var greater = parseInt("2") > parseInt("10");
alert("Is greater than? " + greater);
var less = parseInt("2") < parseInt("10");
alert("Is less than? " + less);