Hello Friends 👋,
Welcome To Infinitbility! ❤️
This tutorial will help you to check value is decimal or not in javascript, here we will you below three ways to check decimal numbers.
- Javascript
Number.isInteger()
Method - Javascript
Math.floor()
Method - Javascript
indexOf()
Method
Let’s start today’s tutorial How to check value is decimal or not in javascript?
Javascript Number.isInteger()
Method
Javascript provide Number.isInteger()
to identify given data is whole number or decimal number.
!Number.isInteger(12.00); // false
!Number.isInteger(12); // false
!Number.isInteger(-12); // false
!Number.isInteger(-12.003); // true
!Number.isInteger(25.00000000000001); // true
!Number.isInteger(25.00000000000000001); // false
Number.isInteger()
is part of the ES6 standard, and you are using an older version, you have should move to the second solution.
Note: Number.isInteger() to find the decimal place, you have “.” After and before 13 digits, the value must be greater than 0.
output
Javascript Math.floor()
Method
For check decimal number, we will use Javascript Math.floor()
Method, it will same work like Number.isInteger()
method.
function isDecimal(n) {
var result = n - Math.floor(n) !== 0;
if (result) return true;
else return false;
}
console.log(isDecimal(12.00)); // false
console.log(isDecimal(12)); // false
console.log(isDecimal(-12)); // false
console.log(isDecimal(-12.002)); // true
console.log(isDecimal(25.000000000001)); // true
console.log(isDecimal(25.000000000000001)); // false
Note: isDecimal(n) to find the decimal place, you have “.” After and before 13 digits, the value must be greater than 0.
output
Javascript indexOf()
Method
If you want to get isDecimal
to provide true
when you pass 0.00
, and 12.00
then you will help indexOf()
Method, it only checks “.” in provided value, and if it is available it will return true
.
!("12.00".indexOf(".") == -1); // true
!("12".indexOf(".") == -1); // false
!("-12".indexOf(".") == -1); // false
!("-12.003".indexOf(".") == -1); // true
!("25.00000000000001".indexOf(".") == -1); // true
!("25.00000000000000001".indexOf(".") == -1); // true
Note: to use indexOf() method you have to first convert value number to string.