Judgment method: 1. Use the "var reg = /^\d (?=\.{0,1}\d $|$)/" statement to define the regular expression object reg; 2. Use " The reg.test(specified value)" statement uses regular expressions to determine whether the specified value is a positive number. If it returns true, it is a positive number, otherwise it is not a positive number.
The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.
javascript determines whether the specified value is a positive number
In javascript, you can use regular expressions to determine whether the specified value is a positive number.
Implementation code:
function validate(num) { if (num != 0) { var reg = /^\d+(?=\.{0,1}\d+$|$)/; if (reg.test(num)) { console.log(num+" 是正数"); } else { console.log(num+" 不是正数"); } } else{ console.log("0既不是正数也不是负数"); } } validate(-1); validate(-2); validate(0); validate(1); validate(1.5); validate(2.365);
Description: The
test() method is used to detect whether a string matches a certain pattern. Returns true if there is a matching value in the string, false otherwise.
Grammar:
RegExpObject.test(string)
Extended knowledge: expressions to check numbers
Numbers: ^[0-9]*$
n-digit number: ^\d{n}$
At least n-digit number: ^\d{n,}$
^\d{ m,n}$
^(0|[1-9][0-9]*)$
^([1-9][0-9]*) (.[0-9]{ 1,2})?$
^(\-)?\d (\.\d {1,2})?$
^(\-|\ )?\d (\.\d ) ?$
^[0-9] (.[0-9]{2})?$
^[0-9] (.[0-9]{1,3})?$
^[1-9]\d*$ or
^([1-9][0-9]* ){1,3}$ or
^\ ?[1-9][0-9]*$
^\-[1-9][]0-9"*$ or
^-[1-9]\d*$
^\d $ or
^[1-9]\d*|0$
^-[1-9]\d*|0$ or
^((-\d )|(0 ))$
^\d (\.\d )?$ or
^[1-9]\d*\.\d*|0\.\d*[ 1-9]\d*|0?\.0 |0$
^((-\d (\.\d )?)|(0 (\.0 )?))$ or
^(-([1-9]\d*\.\d*|0\.\d*[1-9 ]\d*))|0?\.0 |0$
^[1-9]\d*\.\d *|0\.\d*[1-9]\d*$ or
^(([0-9] \.[0-9]*[1-9][0-9] *)|([0-9]*[1-9][0-9]*\.[0-9] )|([0-9]*[1-9][0-9]*)) $
^-([1-9]\d*\.\d*|0\.\d*[1-9 ]\d*)$ or
^(-(([0-9] \.[0-9]*[1-9][0-9]*)|([0-9] *[1-9][0-9]*\.[0-9] )|([0-9]*[1-9][0-9]*)))$
^(-?\d )(\.\d )?$ or
^-?([1-9]\d*\. \d*|0\.\d*[1-9]\d*|0?\.0 |0)$
The above is the detailed content of How to determine whether a specified value is a positive number in javascript. For more information, please follow other related articles on the PHP Chinese website!