Comparison of JavaScript string values
1. Problem background
Today, I encountered a problem in the project: two input boxes, one with a value of 8.4 and the other with a value of 21.3. When comparing the values in the two input boxes, a value greater than 8.4 is displayed.
2. Problem Analysis
First, obtain the value in the input box as a string, while the string comparison is based on the ASCII code. Because the ASCII Code of 8 is larger than the ASCII code of 2, 8.4 is greater than 21.3.
3. Problem Verification
(1) design source code
<Script type = text/javascript> function compareData () {var data1 = document. getElementById (inval ). value; var data2 = document. getElementById (typev ). value; if (data1> data2) {alert (data1 + greater than + data2);} else {alert (data1 + less than or equal to + data2); }}</script>
(2) running result
4. Solution
(1) convert a string to a numeric value
Function compareData () {var data1 = document. getElementById (inval ). value; var data2 = document. getElementById (typev ). value; if (Number (data1)> Number (data2) {alert (data1 + greater than + data2);} else {alert (data1 + less than or equal to + data2 );}}
(2) running result