python-3.x - 试图在浮点数上得到两个小数点,但不断得到 0.0
问题描述
我有一个浮点数,想限制为两位小数。
我尝试了 format() 和 round(),但仍然只得到 0 或 0.0
x = 8.972990688205408e-05
print ("x: ", x)
print ("x using round():", round(x))
print ("x using format():"+"{:.2f}".format(x))
output:
x: 8.972990688205408e-05
x using round(): 0
x using format():0.00
我期待 8.98 或 8.97,具体取决于使用的方法。我错过了什么?
解决方案
您正在使用科学计数法。正如 glhr 在评论中指出的那样,您正在尝试舍入8.972990688205408e-05 = 0.00008972990688205408
. 这意味着尝试四舍五入为 float 类型只会打印0
小数点后的前两个 s,从而导致0.00
. 您必须通过以下方式格式化0:.2e
:
x = 8.972990688205408e-05
print("{0:.2e}".format(x))
这打印:
8.97e-05
您在其中一条评论中询问了如何仅获得 8.97。这是这样做的方法:
y = x*1e+05
print("{0:.2f}".format(y))
输出:
8.97
推荐阅读
- java - 如果所有元素都为空,则流 maptostream 平均值的问题
- date - Fullcalendar 3.9.0 版本的问题,月份和日期值被交换
- python - 安装 Appium 的一些问题
- css - 如何使用 css 标记 GridPane 的选定单元格?
- css - 使用 CSS 在 iframe 中创建透明阴影
- kubernetes - kubernetes:尽管使用率低,但集群自动缩放器没有缩减节点
- angular - 错误:支持使用带有反应式表单指令的 ngModel 输入属性和 ngModelChange 事件已被弃用
- python - 从 JSON 变量中提取值
- javascript - 初始化将在 React 中接收数字的空状态
- angular - NgFor 仅支持绑定到 Iterables,例如 Arrays angular8