How to find the number of decimals in a number minus the trailing zeros in TypeScript

header
Finding the number of decimals in a number minus the trailing zeros can be a useful skill in many situations, such as when dealing with financial data or precision calculations. In Typescript, there are several ways to accomplish this without converting the number to a string.

One approach is to use the built-in Math.log10() function, which returns the base 10 logarithm of a number. We can use this function to calculate the number of decimals in a number by taking the difference between the logarithm of the original number and the logarithm of the integer part of the number. For example:


const num = 123.456;
const intPart = Math.trunc(num);
const decimals = Math.log10(num) - Math.log10(intPart);

console.log(decimals); // 3

However, this approach will not accurately account for trailing zeros, as they will still be counted as part of the decimal component. To address this, we can use a regular expression to remove the trailing zeros and then calculate the number of decimals using the same method as above.


const num = 123.45600;
const numWithoutTrailingZeros = num.toString().replace(/0+$/, '');
const intPart = Math.trunc(numWithoutTrailingZeros);
const decimals = Math.log10(numWithoutTrailingZeros) - Math.log10(intPart);

console.log(decimals); // 2

Another approach is to use the built-in Number.toFixed() function, which returns a string representation of a number with a specified number of decimal places. We can use this function to calculate the number of decimals in a number by passing in a value for the number of decimal places that is greater than the number of actual decimals in the number. For example:


const num = 123.456;
const numWithExtraDecimals = num.toFixed(10);
const decimals = numWithExtraDecimals.length - numWithExtraDecimals.indexOf('.') - 1;

console.log(decimals); // 3

This approach will also accurately account for trailing zeros, as they will be automatically removed by the toFixed() function.

In conclusion, there are several ways to find the number of decimals in a number minus the trailing zeros in Typescript without converting to a string. Whether you use the logarithm approach, the regular expression approach, or the toFixed() approach, you can easily and efficiently calculate the number of decimals in a number in your Typescript code.

Photo by Sathesh D: https://www.pexels.com/photo/closeup-photo-of-black-computer-keyboard-s-left-side-keys-698808/