Round up to Second Decimal Place in Python

后端 未结 11 1222
耶瑟儿~
耶瑟儿~ 2020-11-30 07:16

How can I round up a number to the second decimal place in python? For example:

0.022499999999999999

Should round up to 0.03<

11条回答
  •  情深已故
    2020-11-30 07:51

    Note that the ceil(num * 100) / 100 trick will crash on some degenerate inputs, like 1e308. This may not come up often but I can tell you it just cost me a couple of days. To avoid this, "it would be nice if" ceil() and floor() took a decimal places argument, like round() does... Meanwhile, anyone know a clean alternative that won't crash on inputs like this? I had some hopes for the decimal package but it seems to die too:

    >>> from math import ceil
    >>> from decimal import Decimal, ROUND_DOWN, ROUND_UP
    >>> num = 0.1111111111000
    >>> ceil(num * 100) / 100
    0.12
    >>> float(Decimal(num).quantize(Decimal('.01'), rounding=ROUND_UP))
    0.12
    >>> num = 1e308
    >>> ceil(num * 100) / 100
    Traceback (most recent call last):
      File "", line 301, in runcode
      File "", line 1, in 
    OverflowError: cannot convert float infinity to integer
    >>> float(Decimal(num).quantize(Decimal('.01'), rounding=ROUND_UP))
    Traceback (most recent call last):
      File "", line 301, in runcode
      File "", line 1, in 
    decimal.InvalidOperation: []
    

    Of course one might say that crashing is the only sane behavior on such inputs, but I would argue that it's not the rounding but the multiplication that's causing the problem (that's why, eg, 1e306 doesn't crash), and a cleaner implementation of the round-up-nth-place fn would avoid the multiplication hack.

提交回复
热议问题