how to fix this error ? Exp: 125 < 55

Asked

Viewed 40 times

3

how to correct this error ?

insert 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>

1 answer

2


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

You have to convert that string into a number with parseFloat, parseInt (whole only) or Number.

For example like:

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

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

  • To add source to answer: Comparison Operators

  • The variables firstNumber and secondNumber may have the value NaN if the user fills a text instead of a number.

  • 1

    @Nevershowmyface because, but the purpose of the app is not this, the prompt asks "Insert number". But if you want that security Filipe, you can do ...first Number:", 0)) || 0; at the end of house one of these lines. So it assumes zero if conversion fails.

  • Thank you for the help Sergio, and for the speed of response. so it works well with numeric values , and integers . || 0 (or 0 ) that impressed me hehe , this language is crazy.

  • Great. 'Cause how Number('foo') gives NaN that has value false you can do it like this :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.