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
Using the modulo ( % ) operator The % operator is an arithmetic operator that calculates and returns the remainder after the division of two numbers. If a number is divided by 1, the remainder will be the fractional part. So, using the modulo operator will give the fractional part of a float.
format("%. 2f", 1.23456); This will format the floating point number 1.23456 up-to 2 decimal places, because we have used two after decimal point in formatting instruction %.
Use the toFixed() method to format a number to 2 decimal places, e.g. num. toFixed(2) . The toFixed method takes a parameter, representing how many digits should appear after the decimal and returns the result.
The representation of floating points in JavaScript follows the IEEE-754 format. It is a double precision format where 64 bits are allocated for every floating point.
For anyone wondering how to do this faster (without converting to string), here's a solution:
function precision(a) { var e = 1; while (Math.round(a * e) / e !== a) e *= 10; return Math.log(e) / Math.LN10; }
Edit: a more complete solution with edge cases covered:
function precision(a) { if (!isFinite(a)) return 0; var e = 1, p = 0; while (Math.round(a * e) / e !== a) { e *= 10; p++; } return p; }
One possible solution (depends on the application):
var precision = (12.3456 + "").split(".")[1].length;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With