pythonformattinglatex

Format number using LaTeX notation in Python


Using format strings in Python I can easily print a number in "scientific notation", e.g.

>> print '%g'%1e9
1e+09

What is the simplest way to format the number in LaTeX format, i.e. 1\times10^{+09}?


Solution

  • The siunitx LaTeX package solves this for you by allowing you to use the python float value directly without resorting to parsing the resulting string and turning it into valid LaTeX.

    >>> print "\\num{{{0:.2g}}}".format(1e9)
    \num{1e+09}
    

    When the LaTeX document is compiled, the above code will be turned into enter image description here. As andybuckley points out in the comments, the plus sign might not be accepted by siunitx (I've not tested it), so it may be necessary to do a .repace("+", "") on the result.

    If using siunitx is somehow off the table, write a custom function like this:

    def latex_float(f):
        float_str = "{0:.2g}".format(f)
        if "e" in float_str:
            base, exponent = float_str.split("e")
            return r"{0} \times 10^{{{1}}}".format(base, int(exponent))
        else:
            return float_str
    

    Testing:

    >>> latex_float(1e9)
    '1 \\times 10^{9}'