I am practicing the comparison operators in an if/else statement. My question is that I am expecting the window will give me a True alert, but instead it gave me the False alert. I thought the system will coerce num1 into 97 before it performs the comparison.
Here is my code:
var num1 = "a";
var num2 = 99999;
if (num1 <= num2) {
window.alert("True");
}else {
window.alert("False");
}
I believe the answer to your question has to do with implicit conversions which are happening here. Consider the following line of code:
console.log(99999 + "a")
This will output 99999a, and it won't convert the "a" string to a number. Assuming the same happens with your code snippet, it explains the observations. What we are seeing is consistent with this:
var num1 = "a";
var num2 = "99999";
if (num1 <= num2) {
console.log("True");
} else {
console.log("False");
}
The reason why this is false is that the letter a is lexicographically greater than any single digit character. And since JavaScript is comparing two strings, they are sorting as text, and the first character is all which needs to be examined to render an ordering.
You can use .codePointAt() to get the code point of the charcter
var num1 = "a";
var num2 = 99999;
if (num1.codePointAt(0) <= num2) {
window.alert("True");
} else {
window.alert("False");
}
the above condition is translated as
if(parseInt(num1)<= parseInt(num2)) {
//something
}
parseInt(num1) returns NaN (Not a number) and NaN is, by definition, not less than, equal to, or greater than any other number.
Hence the output is false.
num1="a" is a string and in the comparison num1<=num2, num2 is a number.
Implicit conversion happens here and num2 is converted into a string.
There are several ways to convert a string(of type "345", etc) into a number:
Number()
parseInt()
parseFloat()
bitwise ~~
But the string num1 contains a character so these functions return NaN(Not a number).Hence we cannot convert the string of characters into a number.
Your purpose can be achieved using the charCodeAt() function as follows :
var num1="a";
var num2=9999;
if(num1.charCodeAt(0)<=num2){
window.alert("True");
}else{
window.alert("False");
}
Related
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);
I have a condition in javascript like this :
var a = '60';
var b = '500';
if(a < b) {
console.log('true');
} else {
console.log('false');
}
but the result is false, my expectation should be true, but i tried to compare with php code :
<?php
$a = '60';
$b = '501';
if($a < $b) {
echo 'true';
} else {
echo 'false';
}
?>
and the result is true, if in javascript there is no else if condition it will automatically read to the false condition if the value is not true?
If you're expecting a and b to behave like numbers, don't put them in quotes. That makes them strings.
var a = 60;
var b = 500;
PHP automatically converts those to a number. Try running echo $a - 1; You'll get 59. Also try "00001" == "1". You'll get true! JavaScript doesn't do this kind of detection. Instead JavaScript compares strings alphabetically by their char codes. By alphabetically, I mean that it compares the first characters of each string. If they have the same char codes, it moves on to the next character of each string. If one has a higher char code than the other, it is "greater" than the other string- much like we do when we're determining if "dog" or "dot" comes first alphabetically. In this case, JavaScript would see that 6 has a char code of 54, and 5 has a char code of 53, and it would conclude right then and there that "60" is greater than "500".
PHP converts both strings to numbers before comparing them. If you want the same in JavaScript, use:
if (parseInt(a, 10) < parseInt(b, 10)) {
This is documented:
If you compare a number with a string or the comparison involves numerical strings, then each string is converted to a number and the comparison performed numerically. These rules also apply to the switch statement. The type conversion does not take place when the comparison is === or !== as this involves comparing the type as well as the value.
Good question. The if-else statement is correct, but the variables are not set correctly.
You can use var, but you should use let or const. (but that is just a semantic thing)
The REAL reason you are having issues is that you are putting your numbers as strings..so literally, '60' is not less than '500'.
var a = 60;
var b = 500;
in this case it would come out true. 60 is, in fact, less then 500 =).
Keep up the good work.
You should avoid adding quotes in numbers but in case it is present there then you
can convert to number using parseInt.
Try this:
var a = '60';
var b = '500';
if(parseInt(a) < parseInt(b)) {
console.log('true');
} else {
console.log('false');
}
this is not the case Javascript supports if,else if and else statements but in your code you have declared the values as strings so the compiler is not comparing the strings directly so you have to pass your variables a and b to "Number" function of javascript which will convert strings to integer.
var a = '60';
var b = '500';
var aint = Number(a);
var bint = Number(b);
if(aint < bint) {
console.log('true');
}
else if(aint>bint){
console.log('a is greater');
}else {
console.log('false');
}
Output: true
function NumberAddition(str) {
var nstr = str.match(/[0-9]+/g);
var total = 0;
if (nstr !== null)
for (var i = 0; i < nstr.length; i++) {
total += nstr[i]*1;
}
// code goes here
return total;
}
I was looking at answers in coderbyte.com and this was one of them. My question is about the total += nstr[i]*1 section. if I remove the *1 the answer is concatenated to "2344". However the answer should be 23+4+4=31. why is this?
The *1 forces the string in nstr[i] to be converted to a number. Another way to do that would be
total += +nstr[i];
The * (multiplication) operator is only meaningful for numbers, and the language definition stipulates that when its arguments are not numbers, they should be converted. Of course, if nstr[i] isn't really a number (unlikely in your case, if not impossible) then the result would be a NaN value. Similarly, the unary + operator also forces its operand to be converted to a number.
Multiplying a value by 1 is a way to ensure that it gets converted to a number if it isn't. When you add two things in JavaScript, if either is a string then the operation gets evaluated as string concatenation, not addition. Since the values in nstr were the result of a regular expression match, they are string values, not number values.
You can multiply a value by 1 to make sure that it is treated as a number. The canonical JavaScript way to do this is to use the unary + operator (total += +(nstr[i]);).
> "1"+1
"11"
> 1+"1"
"11"
> 1+1
2
> ("1"*1)+1
2
> (+"1")+1
2
This question already has answers here:
How to add two strings as if they were numbers? [duplicate]
(20 answers)
Closed 8 years ago.
The following doesn't work as expected:
function sum(x,y){
return x + y;
}
document.getElementById('submit').onclick = function(e)
{
//do someting
e.stopPropagation();
var value1 = document.getElementById('v1').value,
value2 = document.getElementById('v2').value;
var newSum = sum(value1, value2);
console.log(newSum);
}
There is something wrong with the values being picked up. It should return the sum and not "1+2=12"
Change
return x + y;
to
return parseInt(x) + parseInt(y);
You have to convert the values to numbers first, before adding them. If the numbers are floats, you can use parseFloat instead of parseInt.
Edit As suggested by RGraham in the comments, its always better to pass the radix (check parseInt's doc) explicitly. So, the code becomes
return parseInt(x, 10) + parseInt(y, 10);
For more accuracy:
function sum(x,y){
return parseFloat(x) + parseFloat(y);
}
You need to parse your value to an int as all values are passed as string in javascript.
value1 = parseInt(document.getElementById('v1').value, 10);
value2 = parseInt(document.getElementById('v2').value, 10);
use
parseInt
Syntax
var num = parseInt(string, radix);
Parameters
string
The value to parse. If string is not a string, then it is converted to one. Leading whitespace in the string is ignored.
radix
An integer that represents the radix of the above mentioned string. Always specify this parameter to eliminate reader confusion and to guarantee predictable behavior. Different implementations produce different results when a radix is not specified.
function sum(x,y){
return parseInt(x,10) + parseInt(y,10);
}
I'm sure this is a simple problem, but I'm comparing negative numbers in javascript i.e.:
var num1 = -83.778;
var num2 = -83.356;
if(num1 < num2)
{
// Take action 1
}
else
{
// Take action 2
}
This script will always take action 2, even though num1 is less than num2. Whats going on here?
How does if (parseFloat(num1) < parseFloat(num2)) work? Maybe your numbers are turning into strings somewhere.
This case also works when we want to compare signed characters for both positive and negative numbers. For my case i had numbers like +3, +4, 0, -1 etc..
Directly using if(num1 > num2) would compare these values as string and we would get output of string comparision.
Thus to compare signed numbers., compare them via if (parseFloat(num1) < parseFloat(num2))
I have the same issue. Workaround for that:
var num1 = -83.778;
var num2 = -83.356;
if((num1 - num2) < 0)
{
// Take action 1
}
else
{
// Take action 2
}
Now Ation 1 will be used.