python调用latex,在Python中使用LaTeX符号格式化数字

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}?

解决方案

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

IUa7y.gif. 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}'

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值