在科学计数法中使用固定指数
考虑以下 Python 片段:
for ix in [0.02, 0.2, 2, 20, 200, 2000]:
iss = str(ix) + "e9"
isf = float(iss)
print(iss + "\t=> " + ("%04.03e" % isf) + " (" + str(isf) + ")")
它生成以下输出:
0.02e9 => 2.000e+07 (20000000.0)
0.2e9 => 2.000e+08 (200000000.0)
2e9 => 2.000e+09 (2000000000.0)
20e9 => 2.000e+10 (20000000000.0)
200e9 => 2.000e+11 (2e+11)
2000e9 => 2.000e+12 (2e+12)
是否可以以某种方式“返回”?也就是说:
2.000e+07 => 0.02e9
2.000e+08 => 0.2e9
2.000e+09 => 2e9
2.000e+10 => 20e9
2.000e+11 => 200e9
2.000e+12 => 2000e9
...我指定我希望指数为e+09
;然后无论我向这个假设函数输入什么数字,都会返回该指数中的数值?是否可以在每种情况下为整数部分和小数部分指定零填充? (即000.0200e9
和020.0000e9
)?
Consider the following Python snippet:
for ix in [0.02, 0.2, 2, 20, 200, 2000]:
iss = str(ix) + "e9"
isf = float(iss)
print(iss + "\t=> " + ("%04.03e" % isf) + " (" + str(isf) + ")")
It generates the following output:
0.02e9 => 2.000e+07 (20000000.0)
0.2e9 => 2.000e+08 (200000000.0)
2e9 => 2.000e+09 (2000000000.0)
20e9 => 2.000e+10 (20000000000.0)
200e9 => 2.000e+11 (2e+11)
2000e9 => 2.000e+12 (2e+12)
Is it possible to "go back" somehow? That is:
2.000e+07 => 0.02e9
2.000e+08 => 0.2e9
2.000e+09 => 2e9
2.000e+10 => 20e9
2.000e+11 => 200e9
2.000e+12 => 2000e9
... I'd specify I want the exponent to be e+09
; and then whatever number I throw at this hypothetic function, returns the number value in that exponent? Would it be possible to specify zero padding for both the whole and the decimal part in each case? (i.e. 000.0200e9
and 020.0000e9
)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
自己格式化(请参阅格式规范迷你语言 ):
输出
解释
{:0=8.3f}
表示“零填充,符号和数字之间的填充,总字段宽度 8,小数点后 3 位,定点格式”。Format it yourself (see Format Specification Mini-Language):
Output
Explanation
{:0=8.3f}
means "zero-pad, pad between the sign and the number, total field width 8, 3 places after the decimal, fixed point format".啊好吧,明白了:
...给出:
抱歉发帖,
干杯!
Ah well, got it:
... gives:
Sorry for posting,
Cheers!
对于几年后仍然遇到的任何人...
您可以使用 python 的 Decimal 和 quantize
https://docs.python.org/3.6/library/decimal.html#decimal.Decimal.quantize
For anyone still coming across this years later...
You can use python's Decimal with quantize
https://docs.python.org/3.6/library/decimal.html#decimal.Decimal.quantize
我编写了一个名为 sciform 的 PyPi 包,它支持这些和许多其他数字格式选项。
我们还可以实现左右补零,这样所有格式化的字符串都有固定的长度。左填充选项控制左填充,右填充可以使用小数位舍入模式来完成。
I've written a PyPi package called sciform that has support for these and many other numerical formatting options.
We can also realize left and right zero padding so all the formatted strings have a fixed length. The left padding options control left padding, and right padding can be accomplished using the decimal place rounding mode.