Home > Article > Web Front-end > How to detect decimals in javascript
Javascript method to detect decimals: 1. Use indexOf(), syntax "String(num).indexOf(".")", if the return value is greater than "-1", it is a decimal. 2. Use regular expressions, the syntax "var rep=/[\.]/;rep.test(num)".
The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.
Javascript method to detect whether it is a decimal
Method 1: Use the indexOf() method
Idea:
Decimals have a decimal point ".
". We can use the indexOf() method to determine the position of the decimal point to determine whether it is a decimal. If the return value of the indexOf() method >-1
is a decimal.
Implementation code:
function isDot(num) { if(String(num).indexOf(".")>-1){ console.log("是小数"); } else{ console.log("不是小数"); } } isDot(121.121);//含有小数点 isDot(454654);//不含小数点
Output result:
是小数 不是小数
Method 2: Use regular expressions to determine whether it is a decimal
function isDot(num) { var rep=/[\.]/; if(rep.test(num)){ console.log("是小数"); } else{ console.log("不是小数"); } } isDot(121.121);//是小数 isDot(454.654);//是小数 isDot(454654);//不是小数
Output result:
是小数 是小数 不是小数
[Recommended learning: javascript advanced tutorial]
The above is the detailed content of How to detect decimals in javascript. For more information, please follow other related articles on the PHP Chinese website!