You can use a formula like:
(x * 1000) % 1 === 0
For numbers with 3 or fewer decimal places, the x*1000
will convert it into an integer. Eg:
1.55 -> 1550
1.555 -> 1555
For numbers with more than 3 decimal places, doing x*1000
won't convert it to an int, it will only shift parts of the number over:
1.5555 -> 1555.5 // still a decimal
The % 1
check then gets the remainder of the above number if it was to be divided by 1. If the remainder is 0, then the number was converted to an integer, if it is more than 0, then x*1000
failed to convert the number to an int, meaning that it has more than 3 decimals:
const validate = x => (x * 1000) % 1 === 0;
console.log(validate(1.5555)); // false
console.log(validate(1.55)); // true
console.log(validate(1.555)); // true
console.log(validate(0.00000001)); // false
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…