【问题标题】:Calculate up to two decimal places in Python [duplicate]在Python中计算最多两位小数[重复]
【发布时间】:2018-06-27 14:44:21
【问题描述】:

我想在我的计算中计算最多两位小数,但我不能

例如:

a = 93
b = 1
c = float(93/1)
print c

我想这样print:

93.00

但它是这样打印的:

93.0

是否有任何功能可以做到这一点或有什么方法可以做到这一点?

【问题讨论】:

  • 没有浮动
  • 它是一个浮点数,因为它有一个小数部分(即使那个小数部分等于 0)。如果它是一个整数,您只需拥有 93

标签: python python-2.7 function integer


【解决方案1】:

对该浮点数使用明确的格式

print("%.2f" % round(c,2))

在 jupyter 上测试它

https://try.jupyter.org/


【讨论】:

  • 感谢您接受答案...我也已经赞成这个问题了:)
【解决方案2】:

首先您必须将代码更改为

c = float(93.0/1.0)

这是因为您使用的是整数除法。

#  eg. 93/2 == 46
#  but 93.0/2 == 46.5 and
#      93.0/2.0 == 46.5
print c

然后要打印 2 个小数位,您必须使用 python 格式

print "%.2f" % c
# 93.00

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-20
    • 1970-01-01
    • 2016-05-12
    • 1970-01-01
    相关资源
    最近更新 更多