How to detect decimals in javascript

青灯夜游
Release: 2023-01-07 11:47:41
Original
10980 people have browsed it

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);//不含小数点
Copy after login

Output result:

是小数
不是小数
Copy after login

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);//不是小数
Copy after login

Output result:

是小数
是小数
不是小数
Copy after login

[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!

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!