0

When i try to compare different numbers, the numbers change but the text part remains the same. This only happens with greater/lesser, and not with NaN or equal case.

Here's my code:

function check() {
    var a = document.getElementById("a").value;
    var b = document.getElementById("b").value;
    
    if (isNaN(a) || isNaN(b) === true) {
        document.getElementById("result").innerHTML = "It's not a number";
    } else {
        if (a > b) {
            document.getElementById("result").innerHTML = "Number " + a + " is greater than number " + b;
        } else if (a == b) {
            document.getElementById("result").innerHTML = "number " + a + " is equal to number " + b;
        } else if (a < b) {
            document.getElementById("result").innerHTML = "number " + a + " is lesser than  number " + b;
        }
    }
}
body {
    background-color: black;
    color: white;
    font-size: 28px;
}
<!DOCTYPE HTML>
<html lang="pl">
    
<head>
    <meta charset="utf-8">
    <title>Check the value of a number compared to the second number</title>
    <script type="text/javascript" src="sprawdzanie.js"></script>
    <link href="style.css" rel="stylesheet">
</head>

<body>

    <input id="a" type="text">
    <input id="b" type="text">
    <input value="Check" type="submit" onclick="check()">
    


    <div id="result"></div>

</body>
    
    
</html>

1
  • Please include the code directly in your question. Commented Jun 12, 2018 at 17:53

1 Answer 1

1

The values a and b are both strings. If you want to compare them like numbers, use parseInt() or parseFloat() on them before you perform the comparison.

So, before the if statement:

a = parseInt(a);
b = parseInt(b);
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, any idea why it is buggy with strings ?
@RKJ The way strings are compared is different from the way numbers are compared; strings are compared character-by-character, which is wrong for numbers if the numbers are of different lengths.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.