Round up to Second Decimal Place in Python

后端 未结 11 1255
耶瑟儿~
耶瑟儿~ 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 08:00

    The python round function could be rounding the way not you expected.

    You can be more specific about the rounding method by using Decimal.quantize

    eg.

    from decimal import Decimal, ROUND_HALF_UP
    res = Decimal('0.25').quantize(Decimal('0.0'), rounding=ROUND_HALF_UP)
    print(res) 
    # prints 0.3
    

    More reference:

    https://gist.github.com/jackiekazil/6201722

提交回复
热议问题