Check if a number have decimals

JavaScript : How to check if a number has a decimal ?

Published 2021-07-16

Check if a number have decimals

const firstNum = 4.43
const secondNum = 4

const hasDecimal = (num) => num % 1 !== 0

console.log(`This number ${hasDecimal(firstNum) ? 'have' : 'do not have'} decimals`)

// 'This number have decimals'

console.log(`This number ${hasDecimal(secondNum) ? 'have' : 'do not have'} decimals`)

// 'This number do not have decimals'

delete decimals

To delete decimals, you can use the .toFixed() method

const firstNum = 4.43

const hasDecimal = (num) => num % 1 !== 0

console.log(`This number ${hasDecimal(firstNum) ? 'have' : 'do not have'} decimals`)

// 'This number have decimals'

console.log(`This number ${hasDecimal(firstNum.toFixed()) ? 'have' : 'do not have'} decimals`)

// 'This number do not have decimals'

Related Tutorials :