在Python中使用格式字符串我可以轻松地以“科学记数法”打印数字,例如
>> print '%g'%1e9
1e+09
将数字格式化为 LaTeX 格式(即 1\times10^{+09})的最简单方法是什么?
The siunitx http://ctan.org/pkg/siunitxLaTeX 包通过允许您直接使用 python 浮点值来解决这个问题,而无需解析结果字符串并将其转换为有效的 LaTeX。
>>> print "\\num{{{0:.2g}}}".format(1e9)
\num{1e+09}
When the LaTeX document is compiled, the above code will be turned into
. 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.
如果使用siunitx
不知怎的,写一个像这样的自定义函数:
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}'
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)