Rounding to significant figures - feature request for math library

Or you could leverage the decimal module. The following is only lightly tested, and I’m not an expert in the decimal module, so could probably be improved:

from decimal import Context

def round_sig(x, n):
    return float(Context(prec=n).create_decimal_from_float(x))

Caveat: I’m not 100% sure that the “precision” used in the decimal module is exactly the same as what the OP means by “significant figures”. It seems like it’s the same concept to me, but so much of this discussion has hinged on fine distinctions that I feel it’s necessary to mention this point…

2 Likes