Two judgment methods: 1. Use the test() function with the regular expression "/[.]/" to check whether the specified value contains a decimal point, the syntax is "/[.]/.test(specified value) ”, if included, it is a decimal, otherwise it is not. 2. Use the indexOf() function to check whether the specified value contains a decimal point. The syntax is "String(specified value).indexOf(".")". If the return value is greater than "-1", it is a decimal, and vice versa.
The operating environment of this tutorial: Windows 7 system, ECMAScript version 6, Dell G3 computer.
Decimals are ".
" with a decimal point. In JavaScript, you can determine whether a number is a decimal by judging whether it contains ".
" with a decimal point. .
Method 1: Use the test() function with regular expressions to check
The test() method is used to detect whether a string matches a certain pattern. , searches the string for text that matches the regular expression. If a match is found, it returns true; otherwise, it returns false.
RegExpObject.test(string)
Regular expression for checking decimals: /[.]/
Example:
function isDot(num) { var rep=/[.]/; if(rep.test(num)){ console.log(num+" 是小数"); } else{ console.log(num+" 不是小数"); } } isDot(121.121);//是小数 isDot(454.654);//是小数 isDot(454654);//不是小数
Method 2: Use the indexOf() function to check
The indexOf() method can return the position where a specified string value first appears in the string.
string.indexOf(searchvalue,start)
Parameters | Description |
---|---|
searchvalue | Required . Specifies the string value to be retrieved. |
start | Optional integer parameter. Specifies the position in the string to begin searching. Its legal values are 0 to string Object.length - 1. If this parameter is omitted, the search will start from the first character of the string. |
Return value: Find the first occurrence of the specified string. If no matching string is found,-1
will be returned.
Just use indexOf() to check the position where the character ".
" first appears in the string. If the return value is equal to -1, it is a decimal, greater than -1 is not a decimal.
Example:
function isDot(num) { if(String(num).indexOf(".")>-1){ console.log(num+" 是小数"); } else{ console.log(num+" 不是小数"); } } isDot(121.121);//含有小数点 isDot(454654);//不含小数点 isDot(45465.4);//含小数点
[Recommended learning:javascript advanced tutorial]
The above is the detailed content of How to determine whether it is a decimal in ES6. For more information, please follow other related articles on the PHP Chinese website!