我有一个像2.32432432423e25python中的数字是计算的结果.
我想将其舍入到3个小数点以获得输出:
2.324e25
Run Code Online (Sandbox Code Playgroud)
我试过用:
x = 2.32432432423e25
number_rounded = round(x, 3)
Run Code Online (Sandbox Code Playgroud)
但是当我打印number_rounded它时输出一个格式相同的数字 x.
如何将显示限制x为仅4位有效数字?
Pau*_*l H 16
您需要为此使用字符串格式:
'{:0.3e}'.format(2.32432432423e25)
原因是round用于指定位置之后的位数,当您的数字为O(25)时,这不是真正相关的.
如果要使用 Python 3.6 中引入的 Python 的 f-string 语法,请在变量后指定格式,用 分隔:,例如:
>>> res = 2.32432432423e25
>>> f'The result is {res:.3e}'
'The result is 2.324e+25'
Run Code Online (Sandbox Code Playgroud)