RainOnMe77
RainOnMe77

Reputation: 145

Lexical comparison of numerical string in javascript

I write a function by html to find out max number.but it get wrong result.

Can anyone say what i'm doing wrong? thanks!

the code as follow

  <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
    <input type="text" id="number1">
    <input type="text" id="number2">
    <input type="text" id="number3">
    <input type="button" id="button" value="求出最大值" onclick="fun()">
    <input type="text" id="maxnumber">
    <script>
        function fun(){
             var number1 = document.getElementById('number1').value;
             var number2 = document.getElementById('number2').value;
             var number3 = document.getElementById('number3').value;
             var max=0;
             max=(number1>number2?number1:number2);
             var max=(max>number3?max:number3);
             document.getElementById('maxnumber').value=max;
         }
        </script>
</body>
</html>

enter image description here

Upvotes: 1

Views: 223

Answers (2)

AL-zami
AL-zami

Reputation: 9066

value property of an input field is string by default. So you are comparing string with string. In javascript string comparison happens lexicographically. Following example will clear the concept behind your problem.

'3'.charCodeAt(0) // evaluates to 51 (ASCII code for 3)
'100'.charCodeAt(0) // evaluates to 49 (ASCII code for 1)

As it compares each character one by one. So when the interpreter finds out that char-code at 0 index for 3 is 51 and for char-code of 1 is 49, so it evaluates '3'>'100' to true

Upvotes: 1

Quentin
Quentin

Reputation: 943981

Reading value of value property of HTMLInputElement object gives string, so you are comparing the string "100" with the string "3".

This does an alphabetic comparison letter by letter until there is a difference and "3" > "1" just like "b" > "a".

Convert your strings to numbers first. e.g. with +, parseInt or Number.

Upvotes: 5

Related Questions