Comparison of JavaScript string values

Source: Internet
Author: User

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

 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.