Home > Web Front-end > JS Tutorial > JavaScript method sharing for judging integers_javascript skills

JavaScript method sharing for judging integers_javascript skills

WBOY
Release: 2016-05-16 16:26:23
Original
1018 people have browsed it

There are two ways to judge integers: regular judgment and literal judgment.

Since word-by-word judgment is too inefficient, it will not be described here. Interested readers can Google it themselves.

1. Regular judgment

Copy code The code is as follows:

var r = /^ ?[1-9][0-9]*$/; //Positive integer
console.log(r.test(1.23));

Effectiveness test:
http://jsfiddle.net/wzsdp9Lc/

Extended function list

Copy code The code is as follows:

"^\d $"  //Non-negative integer (positive integer 0)
"^[0-9]*[1-9][0-9]*$" //Positive integer
"^((-\d )|(0 ))$" //Non-positive integer (negative integer 0)
"^-[0-9]*[1-9][0-9]*$" // Negative integer
"^-?\d $"   //Integer
"^\d (\.\d )?$" //Non-negative floating point number (positive floating point number 0)
"^(([0-9] \.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\. [0-9] )|([0-9]*[1-9][0-9]*))$" //Positive floating point number
"^((-\d (\.\d )?)|(0 (\.0 )?))$" //Non-positive floating point number (negative floating point number 0)
"^(-(([0-9] \.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]* \.[0-9] )|([0-9]*[1-9][0-9]*)))$" //Negative floating point number
"^(-?\d )(\.\d )?$" //Floating point number

2. Rounding judgment

The idea of ​​this method is to determine whether it is equal to the original value after rounding

Copy code The code is as follows:

var num=1.23;
if (parseInt(num) != num) {
console.log(num "is a non-integer");
}
else{
console.log(num "is an integer");
}

Effectiveness test
http://jsfiddle.net/euvn0L1g/1/

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template