【问题标题】:How to round decimal digits always up [duplicate]如何始终向上舍入小数位[重复]
【发布时间】:2016-01-25 04:27:57
【问题描述】:

所以我在四舍五入时遇到了麻烦,这是我的代码:

foo = float(0.21)
bar = float(0.871929)

foobar = foo * bar
Rfoobar = round(foobar,2)

这给了我:

foobar = 0.1831
Rfoobar = 0.18

但我希望 Rfoobar 成为 0.19, 我如何实现它总是在有余数时四舍五入?

我读到了关于 math.ceiling 的文章,但在我的情况下,这似乎不起作用。

非常感谢任何帮助。

【问题讨论】:

  • 乘以 100,上限,除以 100。
  • @Tom Zych 你应该把它放在一个答案中,因为如果没有你的评论,这完全是我会做的。 ;-)
  • 是的,很好,复制。
  • @TomZych 我怎么没想到,我需要更多的咖啡!感谢您的帮助,这行得通!

标签: python python-3.x rounding


【解决方案1】:

调用ceil前后移动小数点即可:

from math import ceil

Rfoobar = ceil(foobar * 100) / 100

如果小数位数不同,您可以执行以下操作:

Rfoobar = ceil(foobar * 10 ** digits) / 10 ** digits

【讨论】:

    【解决方案2】:

    你也可以在四舍五入前加上 0.005:

    >>> for foobar in 0.1831, 0.1801, 0.1800:
            print(foobar, '->', round(foobar + 0.005, 2))
    
    0.1831 -> 0.19
    0.1801 -> 0.19
    0.18 -> 0.18
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多