Get the App
SLTechnology News&Howtos  ›  Development  › 

How does javascript detect decimals

Shulou Source: shulou.com Published: 2022-06-03 17:01:54 10月02日 Update

This article mainly introduces javascript how to detect decimals, has a certain reference value, interested friends can refer to, I hope you can learn a lot after reading this article, the following let the editor take you to understand it.

Javascript decimal detection method: 1, the use of indexOf (), syntax "String (num) .indexOf (". ")", if the return value is greater than "- 1" is a decimal. 2. Using regular expressions, the syntax "var rep=/ [\.] /; rep.test (num)".

The operating environment of this tutorial: windows7 system, javascript1.8.5 version, Dell G3 computer.

Javascript method to detect whether it is a decimal or not

Method 1: using indexOf () method

Train of thought:

Decimals have decimal points. We can use the indexOf () method to determine the location of the decimal point to determine whether it is a decimal, and if the return value of the indexOf () method is more than-1, it is a decimal.

Implementation code:

Function isDot (num) {if (String (num) .indexOf (".") >-1) {console.log ("is a decimal");} else {console.log ("not a decimal");} isDot (121.121); / / isDot (454654) with decimal point; / / without decimal point

Output result:

Is a decimal, not a decimal.

Method 2: use regular expressions to determine whether it is a decimal or not

Function isDot (num) {var rep=/ [\.] /; if (rep.test (num)) {console.log ("is a decimal");} else {console.log ("not a decimal");}} isDot (121.121); / is a decimal isDot (454.654); / / is a decimal isDot (454654); / / is not a decimal

Output result:

Is a decimal is a decimal, not a decimal. Thank you for reading this article carefully. I hope the article "how to detect decimals in javascript" shared by the editor will be helpful to everyone. At the same time, I also hope that you will support us and pay attention to the industry information channel. More related knowledge is waiting for you to learn!

Tags: Decimal method detection decimal point article regular result expression syntax output code value location interest at the same time ideas tutorials more friends environment Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Xiaomi Shulou Technology Microsoft Huawei macOS