【问题标题】:Rounding to two decimal places in Python 2.7?在 Python 2.7 中舍入到小数点后两位?
【发布时间】:2013-07-02 11:51:51
【问题描述】:

使用 Python 2.7 如何将我的数字四舍五入到小数点后两位而不是它给出的 10 位左右?

print "financial return of outcome 1 =","$"+str(out1)

【问题讨论】:

  • 这可能是一罐蠕虫。您是否将财务数据存储在浮点变量中并且现在想要对其进行舍入?在大多数情况下,精确 舍入是不可能的。您可能想要使用整数或Decimals,这取决于您实际尝试执行的操作。
  • 了解格式说明符。您可以直接打印浮点值,而无需将它们转换为字符串。

标签: python python-2.7 rounding


【解决方案1】:

使用内置函数round()

>>> round(1.2345,2)
1.23
>>> round(1.5145,2)
1.51
>>> round(1.679,2)
1.68

或者内置函数format()

>>> format(1.2345, '.2f')
'1.23'
>>> format(1.679, '.2f')
'1.68'

或新样式字符串格式化:

>>> "{:.2f}".format(1.2345)
'1.23
>>> "{:.2f}".format(1.679)
'1.68'

或旧式字符串格式:

>>> "%.2f" % (1.679)
'1.68'

关于round的帮助:

>>> print round.__doc__
round(number[, ndigits]) -> floating point number

Round a number to a given precision in decimal digits (default 0 digits).
This always returns a floating point number.  Precision may be negative.

【讨论】:

  • 字符串格式化方法在使用小数时很有用。例如。 Decimal("{:.2f}".format(val))
  • @PatchRickWalsh 或者简单的Decimal(format(val, '.2f'))
  • 酷!我不知道内置的格式。经过更多探索,我认为如果浮点错误绝对不能接受,这是最准确的舍入方法:Decimal('123.345').quantize(Decimal('1.00'), rounding=decimal.ROUND_HALF_UP) 给你Decimal('123.35')。另一方面,Decimal(format(Decimal('123.345'), '.2f')) 给你Decimal('123.34'),因为 123.345 的二进制表示小于 123.345。
【解决方案2】:

既然您谈论的是财务数字,您不想使用浮点运算。最好使用 Decimal。

>>> from decimal import Decimal
>>> Decimal("33.505")
Decimal('33.505')

使用新型format() 的文本输出格式(默认为半偶数舍入):

>>> print("financial return of outcome 1 = {:.2f}".format(Decimal("33.505")))
financial return of outcome 1 = 33.50
>>> print("financial return of outcome 1 = {:.2f}".format(Decimal("33.515")))
financial return of outcome 1 = 33.52

查看由于浮点不精确导致的舍入差异:

>>> round(33.505, 2)
33.51
>>> round(Decimal("33.505"), 2)  # This converts back to float (wrong)
33.51
>>> Decimal(33.505)  # Don't init Decimal from floating-point
Decimal('33.50500000000000255795384873636066913604736328125')

四舍五入财务价值的正确方法

>>> Decimal("33.505").quantize(Decimal("0.01"))  # Half-even rounding by default
Decimal('33.50')

在不同的交易中有其他类型的舍入也很常见:

>>> import decimal
>>> Decimal("33.505").quantize(Decimal("0.01"), decimal.ROUND_HALF_DOWN)
Decimal('33.50')
>>> Decimal("33.505").quantize(Decimal("0.01"), decimal.ROUND_HALF_UP)
Decimal('33.51')

请记住,如果您要模拟收益结果,您可能必须在每个利息期进行舍入,因为您无法支付/接收美分,也无法接收超过美分的利息。对于模拟,由于固有的不确定性,通常只使用浮点,但如果这样做,请始终记住错误就在那里。因此,即使是固定利率投资的回报也可能因此而有所不同。

【讨论】:

    【解决方案3】:

    你也可以使用str.format()

    >>> print "financial return of outcome 1 = {:.2f}".format(1.23456)
    financial return of outcome 1 = 1.23
    

    【讨论】:

      【解决方案4】:

      使用便士/整数时。您会遇到 115(如 $1.15)和其他数字的问题。

      我有一个函数可以将整数转换为浮点数。

      ...
      return float(115 * 0.01)
      

      这在大多数情况下都有效,但有时它会返回 1.1500000000000001 之类的东西。

      所以我把函数改成这样返回了……

      ...
      return float(format(115 * 0.01, '.2f'))
      

      这将返回1.15。不是 '1.15'1.1500000000000001(返回浮点数,而不是字符串)

      我主要发布这个,所以我可以记住我在这种情况下做了什么,因为这是谷歌的第一个结果。

      【讨论】:

      • 正如另一个答案所指出的,财务数据使用十进制数,而不是浮点数。
      • 我最终将大部分内容都转换为整数。它似乎更容易使用。但是,我并没有做任何与零碎硬币打交道的事情。
      【解决方案5】:

      我认为最好的方法是使用format() 函数:

      >>> print("financial return of outcome 1 = $ " + format(str(out1), '.2f'))
      // Should print: financial return of outcome 1 = $ 752.60
      

      但我不得不说:在处理财务价值时不要使用圆形或格式。

      【讨论】:

      • format 要求 f 格式的非字符串。如果没有,你会得到一个 ValueError。正确的代码是:format(out1, '.2f') 不强制转换为字符串
      【解决方案6】:

      当我们使用round()函数时,它不会给出正确的值。

      您可以使用, 圆形(2.735)和圆形(2.725)

      请使用

      import math
      num = input('Enter a number')
      print(math.ceil(num*100)/100)
      

      【讨论】:

      • 请添加您测试的示例、结果以及您认为它们有什么问题。
      • import math num = input('输入一个数字') numr = float(round(num, 2)) print numr
      【解决方案7】:
      print "financial return of outcome 1 = $%.2f" % (out1)
      

      【讨论】:

        【解决方案8】:

        一个相当简单的解决方法是先将float转换为string,选择前四个数字的子字符串,最后将子字符串转换回float。 例如:

        >>> out1 = 1.2345
        >>> out1 = float(str(out1)[0:4])
        >>> out1
        

        可能不是超级高效但简单且有效:)

        【讨论】:

        • 这种方法很不可靠。如果您的值在小数点前多于一位,则您不会得到两个想要的小数位。负数也有同样的问题。
        【解决方案9】:

        四舍五入到下一个 0.05,我会这样做:

        def roundup(x):
            return round(int(math.ceil(x / 0.05)) * 0.05,2)
        

        【讨论】:

          猜你喜欢
          • 2014-02-10
          • 1970-01-01
          • 1970-01-01
          • 2012-05-09
          • 1970-01-01
          • 2013-12-25
          • 2022-01-02
          • 2012-08-29
          相关资源
          最近更新 更多