Reputation: 49
When I use greater or less than symbol (< >
) in code it returns a wrong result - for example when I enter 2 and 10, It returns 2 is bigger and 10 is smaller!
I know that I can use Math.max(a,b)
then it returns the right result but I want to know: why does it return the wrong result? Am I wrong?
Please explain this for me. Thank you. (;
Here is the code:
<!DOCTYPE html>
<html>
<head>
<title>showing the bigger an smaller number</title>
<meta charset="utf-8">
<script>
function b(){
var a=document.getElementById("a").value;
var b=document.getElementById("b").value;
if (a>b){document.getElementById("o").innerHTML="a is bigger : "+a}
else {if (a<b){document.getElementById("o").innerHTML="b is bigger : "+b}}
}
function k(){
var a=document.getElementById("a").value;
var b=document.getElementById("b").value;
if (a>b){document.getElementById("o").innerHTML="b is smaller : "+b}
else {if (a<b){document.getElementById("o").innerHTML="a is smaller : "+a}}
}
</script>
<style>
small {
font-family:"Comic Sans MS", cursive;
color:#666;
}
input {
height:30px;
width:175px;
}
</style>
</head>
<body>
<input type="number" id="a" placeholder="type first Number here"></input><b> </b>
<input type="number" id="b" placeholder="type second number here"></input>
<br>
<button onClick="b();">show me the bigger Number</button>
<button onclick="k();">show me the smaller Number</button>
<br><b></b>
<br><small id="o"> </small>
</body>
</html>
Sorry if my English was bad.
Upvotes: 1
Views: 157
Reputation: 51634
You can use the !=
(not equal) or !==
(not identical) relational operators instead of <>
.
Upvotes: 2
Reputation: 53198
Try parsing the values as floats. At the moment, you're comparing strings:
var a = parseFloat(document.getElementById("a").value),
b = parseFloat(document.getElementById("b").value);
Of course, this is going to cause problems if the user enters something other than a valid numerical value...
Upvotes: 4