【问题标题】:Rounding - best way how to do it? [duplicate]四舍五入 - 最好的方法怎么做? [复制]
【发布时间】:2022-01-11 19:44:51
【问题描述】:

我的情况是我有浮点数(如 1.122、1.3232、1.22222)我需要始终按照数学规则将其四舍五入到小数点后 2 位:如果第三个是 5 或更高,则向上,向下是第三个低于5.

像这样(回合前 -> 回合后):

1.123 -> 1.12
1.1250 -> 1.13
1.0050 -> 1.01
1.0000 -> 1.00
1.00001 -> 1.00

(“.”后总是两个)

Python 中的哪种方式最适合这个? 我尝试了圆形函数、格式、numpy、十进制,但有时总是失败。提示赞赏!

【问题讨论】:

  • 这能回答你的问题吗? How to round numbers
  • 有时失败是什么意思?为什么你提到的功能都不适合你?
  • “我尝试了圆形函数、格式、numpy、十进制,但有时总是失败。”它是如何失败的?什么时候失败了?
  • A float 没有“小数位”的概念。数字1.00001.001. 是完全相同的值。您是否尝试格式化数字,例如用于打印或写入文件?
  • 我对这个问题投了反对票,因为 OP 拒绝澄清他们是否要对数字进行四舍五入或格式化。

标签: python rounding


【解决方案1】:

有一个有用的函数“round”:

round(1.123, 2) -> 1.12

round(1.12345, 3) -> 1.123

更新

如果你想得到算术舍入,你可以使用数学包和你自己的函数:

import math
def arithmetic_round(val):
    x = 0
    if (float(val) * 100 % 1) >= 0.5:
        x = math.ceil(val*100)/100
    else:
        x = math.floor(val*100)/100
    return format(x, '.2f')

timgeb 是正确的 - 在 Python 中,1.0050 是 1.004999。

这就是为什么我建议将 0.5 更改为 0.49:

import math
def arithmetic_round(val):
    x = 0
    if (float(val) * 100 % 1) >= 0.49:
        x = math.ceil(val*100)/100
    else:
        x = math.floor(val*100)/100
    return format(x, '.2f')


arithmetic_round(1.123) -> 1.12
arithmetic_round(1.1250) -> 1.13
arithmetic_round(1.0050) -> 1.01
arithmetic_round(1.0000) -> 1.00
arithmetic_round(1.00001) -> 1.00

【讨论】:

  • round(1.125, 2) -> 1.12 我需要:1.125 -> 1.13
猜你喜欢
  • 1970-01-01
  • 2018-01-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-13
  • 2017-12-02
相关资源
最近更新 更多