It is important to note that I am not looking for a rounding function. I am looking for a function that returns the number of decimal places in an arbitrary amount, a simplified decimal representation. That is, we have the following:
decimalPlaces(5555.0); //=> 0 decimalPlaces(5555); //=> 0 decimalPlaces(555.5); //=> 1 decimalPlaces(555.50); //=> 1 decimalPlaces(0.0000005); //=> 7 decimalPlaces(5e-7); //=> 7 decimalPlaces(0.00000055); //=> 8 decimalPlaces(5.5e-7); //=> 8
My first instinct was to use string representations: split by '.' , then to 'e-' and do the math, for example (example - detailed):
function decimalPlaces(number) { var parts = number.toString().split('.', 2), integerPart = parts[0], decimalPart = parts[1], exponentPart; if (integerPart.charAt(0) === '-') { integerPart = integerPart.substring(1); } if (decimalPart !== undefined) { parts = decimalPart.split('e-', 2); decimalPart = parts[0]; } else { parts = integerPart.split('e-', 2); integerPart = parts[0]; } exponentPart = parts[1]; if (exponentPart !== undefined) { return integerPart.length + (decimalPart !== undefined ? decimalPart.length : 0) - 1 + parseInt(exponentPart); } else { return decimalPart !== undefined ? decimalPart.length : 0; } }
For my examples above, this function works. However, I am not satisfied until I checked all the possible values, so I threw out Number.MIN_VALUE .
Number.MIN_VALUE; //=> 5e-324 decimalPlaces(Number.MIN_VALUE); //=> 324 Number.MIN_VALUE * 100; //=> 4.94e-322 decimalPlaces(Number.MIN_VALUE * 100); //=> 324
At first it looked reasonable, but then on a double take, I realized that 5e-324 * 10 should be 5e-323 ! And then it hit me: I am dealing with the effects of quantizing very small numbers. Before storage, not only are numbers quantized; in addition, some numbers stored in binary format have unnecessarily long decimal representations, so their decimal representations are truncated. This is unfortunate for me because it means that I cannot get their true decimal precision using their string representations.
So, I come to you, the StackOverflow community. Do any of you know a reliable way to get accurate accuracy after a decimal point?
The purpose of this function, if anyone asks, is intended to be used in another function that converts a float into a simplified fraction (i.e. returns a relatively unit numeric numerator and a nonzero natural denominator). The only missing element of this external function is a reliable way to determine the number of decimal places in the float so that I can multiply it by the corresponding power of 10. I hope I overdo it.
javascript decimal floating-point precision fractions
Milosz Mar 02 2018-12-12T00: 00Z
source share