For integers [1, 2, 4, 8, 16, ...] I can use this function:
const validate = num => (num & num - 1) == 0;
Is there an elegant similar way to do it with decimal numbers without using loops?
- 0.001
- 0.002
- 0.004
- ...
- 2.048
And it should be possible to use any number of digits after the decimal point based on a initial value.
- 0.0001 (initial value)
- 0.0002
- 0.0004
- 0.0016
- ...
- 1.6384
Now I use the function to determine if there are numbers after decimal comma and count them:
countDecimals(num) {
if (Math.floor(num.valueOf()) === num.valueOf()) return 0;
return num.toString().split(".")[1].length || 0;
}
and then I use it:
validateEntryValue(entryValue) {
const decimalsQuantity = this.countDecimals(entryValue);
if (decimalsQuantity) {
const numToMul = Math.pow(10, decimalsQuantity);
return ((entryValue * numToMul) & (entryValue * numToMul) - 1) == 0;
}
return (entryValue & entryValue - 1) == 0;
}
But some result values fail the tests:
- 0.001 (initial value)
- 0.002
- 0.004
- 0.016
- 0.02 (should not to be validated because an initial value is not 0.01)