Why does my code think 60 is greater than 135?
I want to get a larger number and subtract a smaller number (input value) even if they are in the wrong order when you put them in the input like -1 = inputX / 1 = inputY then 1 = more and - 1 less it works with different numbers, but these curious ones are breaking it, why what did I do wrong? why does he think 60 is more than 135? look at img ...
<script type="text/javascript">
var x;
var y;
var big;
var small;
var result;
function calcT() {
x = document.getElementById("inputX").value;
y = document.getElementById("inputY").value;
//result = x - y;
if(x > y) {
big = x;
small = y;
} else if(x < y) {
big = y;
small = x;
}
result = parseInt(big) - parseInt(small);
document.getElementById("resultHere").innerHTML = result;
}
source to share
Please parse to see integer inputX and inputY before comparison.
It treats inputX and inputY as a string.
therefore '135'> '65' is false & & '65'> '135' is true.
var x; var y; var big; var small; var result;
function calcT() {
x = document.getElementById("inputX").value;
y = document.getElementById("inputY").value; //result = x - y;
x= parseInt(x); // Missing point <--
y= parseInt(y); // Missing point <--
if(x > y) { big = x; small = y;
} else if(x < y) {
big = y; small = x; }
result = big - small;
document.getElementById("resultHere").innerHTML = result;
}
source to share
It would be easier to do this:
var result = Math.abs(x-y);
This will save you the hassle of using the if-else ladder and will basically give you the same thing in 1 line.
And the problem is that you are comparing strings instead of numbers as indicated by others. You can do something like:
var x = parseInt(document.getElementById("inputX").value);
var y = parseInt(document.getElementById("inputY").value);
var result = (x<y) ? y-x : x-y;
source to share
You are comparing two strings. You need to parse them before the ints before doing the comparison:
console.log('as strings...', '123' > '50')
console.log('as numbers...', Number('123') > Number('50'))
source to share