javascript – how to fix this error? exp: 125 < 55

Question:

how to fix this error?

if you enter firstNumber = 125 , and secondNumber = 055
the result: 125 > 055
if firstNumber = 125 and secondNumber = 55
result: 125 < 55

book code: Javascriptme page 23 and 24.

<body>
    <SCRIPT LANGUAGE="JavaScript">
        var firstNumber, //declare first variable
            secondNumber; //declare second variable
        firstNumber = window.prompt("Enter first Number:", 0);
        secondNumber = window.prompt("Enter second integer:", "0");

        document.writeln("<H1>Comparison Output</H1>");
        document.writeln("<TABLE BORDER = '2' WIDTH = '100%'>"); // Creates table   

        if (firstNumber == secondNumber)
            document.writeln("<TR><TD>" + firstNumber + " = " + secondNumber +
                "</TD></TR>"); // Creates rows and columns
        if (firstNumber != secondNumber)
            document.writeln("<TR><TD>" + firstNumber + " Not equal to " + secondNumber +
                "</TD></TR>");

        if (firstNumber > secondNumber)
            document.writeln("<TR><TD>" + firstNumber + " > " + secondNumber +
                "</TD></TR>")
        else
            document.writeln("<TR><TD>" + firstNumber + " < " + secondNumber +
                "</TD></TR>");
        // Display results
        document.writeln("</TABLE>");

    </SCRIPT>
</body>

Answer:

The problem is that the result of window.prompt("Enter first Number:", 0); it is a string and not a number . So what's happening is you're comparing text, and then it counts the length first.

You have to convert this String to a number with parseFloat , parseInt (only for integers) or Number .

For example like this:

firstNumber = Number(window.prompt("Enter first Number:", 0));
secondNumber = Number(window.prompt("Enter second integer:", "0"));

Example: https://jsfiddle.net/8a9rd1rt/

Scroll to Top