maciejwww
maciejwww

Reputation: 1196

How to round number's fractional part to significant figures?

I'd like to automatically round numbers to x significant figures, but only their fractional part.

Desired output:

123 >>> 123.00
123.123 >>> 123.12
1.12 >>> 1.12
0.1 >>> 0.10
0.1234 >>> 0.12
0.01234 >>> 0.012
0.0001254 >>> 0.00013

I'm trying to achieve the most simple solution.

Upvotes: 0

Views: 65

Answers (1)

maciejwww
maciejwww

Reputation: 1196

I've figured out such a solution:

def round_to_frac_sigfig(num, sigfigs):
    sigfig_pos = int(floor(log10(abs(num))))
    if sigfig_pos >= 0:
        formatter = "{:.%df}" % sigfigs
        return formatter.format(num)
    else:
        ndigits = -sigfig_pos + sigfigs - 1
        formatter = "{:.%df}" % ndigits
        return formatter.format(num)

If you don't care about the trailing zeros, here's a shorter solution:

def round_to_frac_sigfig(num, sigfigs):
    sigfig_pos = int(floor(log10(abs(num))))
    if sigfig_pos >= 0:
        return round(num, sigfigs)
    else:
        return round(num, -sigfig_pos + sigfigs - 1)

Upvotes: 1

Related Questions