Determine precision and scale of particular number in Python

Getting the number of digits to the left of the decimal point is easy:

int(log10(x))+1

The number of digits to the right of the decimal point is trickier, because of the inherent inaccuracy of floating point values. I’ll need a few more minutes to figure that one out.

Edit: Based on that principle, here’s the complete code.

import math

def precision_and_scale(x):
    max_digits = 14
    int_part = int(abs(x))
    magnitude = 1 if int_part == 0 else int(math.log10(int_part)) + 1
    if magnitude >= max_digits:
        return (magnitude, 0)
    frac_part = abs(x) - int_part
    multiplier = 10 ** (max_digits - magnitude)
    frac_digits = multiplier + int(multiplier * frac_part + 0.5)
    while frac_digits % 10 == 0:
        frac_digits /= 10
    scale = int(math.log10(frac_digits))
    return (magnitude + scale, scale)

Leave a Comment