【问题标题】:Round an answer to 2 decimal places in Python在 Python 中将答案四舍五入到小数点后 2 位
【发布时间】:2012-11-07 22:49:03
【问题描述】:

我遇到的问题是将结果四舍五入到小数点后 2 位。我的应用程序得到了正确的结果,但是,我很难像使用货币那样使应用程序四舍五入到最接近的小数

cost = input("\nEnter the 12 month cost of the Order: ")
cost = float(cost)

print("\n12 Month Cost:",
  cost * 1,"USD")
print("6 Month Cost:",
  cost * 0.60,"USD")
print("3 Month Cost:",
  cost * 0.36,"USD")

例如,如果 12 个月的价格是 23 美元,那么 6 个月的价格是 13.799999999999999,但我希望它显示 13.80

我环顾了谷歌以及如何对数字进行四舍五入,但在四舍五入方面找不到太多帮助。

【问题讨论】:

  • 只是关于 12 个月、6 个月和 3 个月成本的乘数的一点...我认为这些应该是 1、0.5 和 0.25,而不是 1、0.6 和 0.36。您正在服用 12 个月(6 个月)的 50% 和 12 个月(3 个月)的 25%。
  • @dhj OP 可能正在编写一个订阅系统,该系统根据订阅的时间长度提供最佳折扣。订阅 6 个月只需 13.80 美元,但订阅 12 个月比一年便宜 4.60 美元!
  • @kreativitea ... 好点!我做了很多数学/科学数据处理。就我而言,这是令人尴尬的假设。
  • @dhj 别担心,在我看到你已经写了它之前,我和你有同样的想法……只有在你写了你的评论之后,我才提出了例外;我敢肯定,如果我们以不同的顺序到达,我们的位置可能会颠倒过来。

标签: python currency rounding


【解决方案1】:

一个经典的方法是乘以 100,加上 0.5(这是四舍五入)和 int() 结果。现在您有了四舍五入的美分数,再除以 100 即可得到四舍五入的浮点数。

cost = 5.5566
cost *= 100 # cost = 555.66
cost += 0.5 # cost = 556.16
cost = int(cost) # cost = 556
cost /= float(100) # cost =  5.56

cost = 5.4444
cost = int(( cost * 100 ) + 0.5) / float(100) # cost = 5.44

【讨论】:

    【解决方案2】:

    您应该使用格式说明符:

    print("6 Month Cost: %.2fUSD" % (cost * .6))
    

    更好的是,您根本不应该依赖浮点数,而是使用decimal 模块,它可以让您获得任意精度并更好地控制舍入方法:

    from decimal import Decimal, ROUND_HALF_UP
    def round_decimal(x):
      return x.quantize(Decimal(".01"), rounding=ROUND_HALF_UP)
    
    cost = Decimal(input("Enter 12 month cost: "))
    print("6 Month Cost: ", round_decimal(cost * Decimal(".6")))
    

    【讨论】:

    • 超越货币格式,如果我们对常规 Python 十进制数字使用格式说明符,它通常不会比使用 decimal 模块具有更好的性能吗?
    【解决方案3】:

    如果您只想将其作为字符串,格式会有所帮助:

    format(cost, '.2f')
    

    此函数返回一个字符串,该字符串的格式与第二个参数中定义的一样。因此,如果 cost 包含 3.1418,上面的代码将返回字符串 '3.14'。

    【讨论】:

      【解决方案4】:

      如果您只想打印,字符串格式将起作用:

      print("\n12 Month Cost:%.2f USD"%(cost*1))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-06-12
        • 1970-01-01
        • 2012-01-03
        相关资源
        最近更新 更多