how to correct this error? Exp: 125 55

3

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 pag 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>
    
asked by anonymous 02.07.2016 / 12:35

1 answer

3

The problem is that window.prompt("Enter first Number:", 0); is a string, not a number . So what is happening is that you are comparing text, and then count the length first.

You need 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: link

    
02.07.2016 / 12:39