【问题标题】:Python Rounding [duplicate]Python舍入[重复]
【发布时间】:2016-01-23 13:02:55
【问题描述】:

我正在处理以.25 或.75 结尾的纬度/经度。我想提示用户输入纬度/经度,并让程序将其舍入到以 .25 或 .75 结尾的纬度/经度。我不能四舍五入到 0.00 或 0.5,只有 0.25 或 0.75。

例如,如果用户输入 43.04,我需要 Python 将其四舍五入为 43.25。

我正在使用 Enthought Canopy Python 发行版,并且是 Python 新手。对此有何建议?

【问题讨论】:

  • 你用的是哪个版本的python?
  • 您好!欢迎来到 StackOverflow 詹姆斯。如果你用谷歌搜索“python 中的舍入”,我想你会找到答案的。
  • 试试0.5 * math.floor(2.0 * your_number) + 0.25
  • 它们可以以.00.5 结尾吗?
  • 43.45 这样的东西应该四舍五入到什么程度? 43.5呢?

标签: python rounding precision


【解决方案1】:

这可以用作自定义舍入函数:

def customRound(num, d = [0.0, 0.25, 0.75, 1.0]): # you can change this list to any e.g. [0.0, 0.1, 0.4, 0.9, 1.0]
     dec = num%1
     r = num - dec
     round_dec = min([(abs(i - dec),i) for i in d])[1]
     return r + round_dec

你可以这样使用它:

>>> customRound(9.34)
9.25
>>> customRound(9.4)
9.25
>>> customRound(9.98)
10.0
>>> customRound(9.8)
9.75

【讨论】:

    猜你喜欢
    • 2013-04-02
    • 2011-11-22
    • 2020-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多