JSFiddle - React, Tailwind, and code Playground
JavaScript
function precision(a) { // Mourner's answer
if (!isFinite(a)) return 0;
var e = 1, p = 0;
while (Math.round(a * e) / e !== a) { e *= 10; p++; }
return p;
}
let MAX_DECIMAL_PRECISION = 9; /* can be increased, but must be <= 15 */
let maxDecimalPrecisionFloat = 10**MAX_DECIMAL_PRECISION;
function precisionRobust(a) {
if (!isFinite(a)) return 0;
var e = 1, p = 0;
while ( ++p<=MAX_DECIMAL_PRECISION && Math.round( ( Math.round(a * e) / e - a ) * maxDecimalPrecisionFloat ) !== 0) e *= 10;
return p-1;
}
console.log( precision(0.1+0.2) ); // this breaks
console.log( precisionRobust(0.1+0.2) ); // this is OK
console.log( precisionRobust(123456.1+123456.2) ); // this is OK
console.log( precisionRobust(1234567.1+1234567.2) ); // this might break, though it does not here.