def round_to_n(x, n): " Round x to n significant figures " return round(x, -int(py.floor(py.sign(x) * py.log10(abs(x)))) + n) def str_fmt(x, n=2): " Format x into nice Latex rounding to n" power = int(py.log10(Round_To_n(x, 0))) f_SF = Round_To_n(x, n) * pow(10, -power) return r"${}\cdot 10^{}$".format(f_SF, power) >>> x = 1203801.30201 >>> str_fmt(x) $1.2\\cdot 10^6$
There are many options for how to parameterize this, for example, you could specify the exponent ( y ) rather than automatically generate it, but the principle remains the same.
source share