use*_*818 11 python string numbers
我在科学记数法中的数字(因此,作为字符串),如:
8.99284722486562e-02
Run Code Online (Sandbox Code Playgroud)
但我想将它们转换为:
0.08992847
Run Code Online (Sandbox Code Playgroud)
有没有内置功能或任何其他方式来做到这一点?
m0d*_*dem 11
我很确定你可以这样做:
float("8.99284722486562e-02")
# and now with 'rounding'
"{:.8f}".format(float("8.99284722486562e-02"))
Run Code Online (Sandbox Code Playgroud)
科学记数法可以转换为浮点数float。
\xc2\xa0 \xc2\xa0输入[1]:\xc2\xa0 float("8.99284722486562e-02")
\n输出[1]:\xc2\xa0 0.0899284722486562\n
可以float用formatand 然后进行舍入float可以在字符串上使用以返回最终的舍入浮点数。
\xc2\xa0 \xc2\xa0In [2]: \xc2\xa0float("{:.8f}".format(float("8.99284722486562e-02")))
\nOut [2]: \xc2\xa0 0.08992847
2022 年编辑无声音的评论:
\n\n以下解决方案适用于较大数量。
\n解决方案1)
\nimport numpy as np\n\nprint(np.format_float_positional(1.32456e-12, trim=\'-\'))\nprint(np.format_float_positional(1.32456e-24, trim=\'-\'))\nprint(np.format_float_positional(1.32456e12, trim=\'-\'))\nprint(np.format_float_positional(1.32456e24, trim=\'-\'))\n\n# Output: 0.00000000000132456\n# 0.00000000000000000000000132456\n# 1324560000000\n# 1324560000000000000000000\nRun Code Online (Sandbox Code Playgroud)\n解决方案2)
\n与上面相同,这次使用 lambda 函数接受
\nimport numpy as np\n\npretty_print = lambda x: np.format_float_positional(x, trim="-")\n\nprint(pretty_print(1.32456e-12))\nprint(pretty_print(1.32456e-24))\nprint(pretty_print(1.32456e12))\nprint(pretty_print(1.32456e24))\n\n# Output: 0.00000000000132456\n# 0.00000000000000000000000132456\n# 1324560000000\n# 1324560000000000000000000\nRun Code Online (Sandbox Code Playgroud)\n
我之所以做出这个答案,是因为投票最多的人有错误信息,所以我可以解释我的改进。
TL;DR:使用("%.17f" % n).rstrip('0').rstrip('.')
默认情况下,如果开头有 5 个或更多零,则 Python 格式为科学记数法。
0.00001/1e-05格式为"1e-05".
0.0001/1e-04格式为"0.0001".
所以当然8.99284722486562e-02会格式化为"0.0899284722486562"已经。
一个更好的例子是8.99284722486562e-05. ( 0.00008992847224866)
我们可以轻松地格式化为与默认情况下"%f"相同的原始小数位"%.6f"。
"%f" % 8.99284722486562e-05产生'0.000090'.
"%f" % 0.01产生'0.010000'.
默认情况下,浮点数最多显示 17 位小数。
0.1234567898765432123- (19 dp 输入)
0.12345678987654321 - (17 dp 输出)
所以如果我们这样做了,"%.17f" % 8.99284722486562e-02我们会得到'0.08992847224865620'. (注意额外的 0)
但是如果我们这样做了,"%.17f" % 0.0001我们肯定不会想要'0.00010000000000000'.
因此,要删除尾随零,我们可以执行以下操作("%.17f" % n).rstrip('0').rstrip('.')
:(请注意,我们还删除了小数点,以防数字没有剩余小数)
还有对应的%f:
%f显示标准记数法
%e显示科学记数法
%g显示默认值(如果有 5 个或更多零,则为科学记数法)
| 归档时间: |
|
| 查看次数: |
29972 次 |
| 最近记录: |