Home >Web Front-end >Front-end Q&A >How to detect decimals in javascript

How to detect decimals in javascript

青灯夜游
青灯夜游Original
2021-09-08 18:24:3411188browse

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)".

How to detect decimals in javascript

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!

Statement:
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