Compare number sizes in JavaScript

Source: Internet
Author: User

To do the project, encountered a very tangled problem, is to get the two value comparison, but there is a single number than the two-digit large case.
At first, I thought it was wrong to write, checked several times, with IE tune down, realize that it should be the wrong comparison method. Just think of the past has also encountered this situation, the reason is that JS default comparison string, first compare two first characters, the same and then compare the second one, and so on.
Therefore, for the comparison of numbers, first to convert to a number, and then compare, there will be no error.
JS in the numerical comparison, as follows:

var id=document.pageaction.pagenow.value;-->4var count=document.pageaction.count.value;-- >30 alert (id>count); // The result is true

Alert result is true because the JS default comparison string, first compares two first characters, the same compares the second one, and so on

How to resolve:
Use parseint (ID) for integer conversions:

Alert (parseint (ID) >parseint (count)); // The result is Falsealert (Eval_r (ID) >eval_r (count)); // The eval () function is used to calculate a code string without referencing any particular object. 

Compare number sizes in JavaScript

Related Article

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.