EN
JavaScript - number has decimal part
8
points
In this short article, we would like to show how to check if number has decimal part using JavaScript.
Practical example:
// ONLINE-RUNNER:browser;
const hasDecimalPart = value => {
return isFinite(value) && (value % 1.0 !== 0);
};
// Usage example:
console.log(hasDecimalPart( 5 )); // false
console.log(hasDecimalPart( 3.14 )); // true
console.log(hasDecimalPart( -3.14 )); // true
console.log(hasDecimalPart( 0.123 )); // true
console.log(hasDecimalPart( -0.123 )); // true
console.log(hasDecimalPart( '+3.14' )); // true
console.log(hasDecimalPart( '-3.14' )); // true
console.log(hasDecimalPart( NaN )); // false
console.log(hasDecimalPart( 'foo' )); // false
console.log(hasDecimalPart( -Infinity )); // false
console.log(hasDecimalPart( +Infinity )); // false