What I would like to have is the almost opposite of Number.prototype.toPrecision(), meaning that when i have number, how many decimals does it have? E.g.
(12.3456).getDecimals() // 4
What I would like to have is the almost opposite of Number.prototype.toPrecision(), meaning that when i have number, how many decimals does it have? E.g.
(12.3456).getDecimals() // 4
One possible solution (depends on the application):
Does the following approaches work?
or
Basing on @blackpla9ue comment and considering numbers exponential format:
Here are a couple of examples, one that uses a library (BigNumber.js), and another that doesn't use a library. Assume you want to check that a given input number (
inputNumber
) has an amount of decimal places that is less than or equal to a maximum amount of decimal places (tokenDecimals
).With BigNumber.js
Without BigNumber.js
Based on @boolean_Type's method of handling exponents, but avoiding the regex:
For anyone wondering how to do this faster (without converting to string), here's a solution:
Edit: a more complete solution with edge cases covered: