Round up to Second Decimal Place in Python

后端 未结 11 1229
耶瑟儿~
耶瑟儿~ 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:41

    def round_up(number, ndigits=None):
        # start by just rounding the number, as sometimes this rounds it up
        result = round(number, ndigits if ndigits else 0)
        if result < number:
            # whoops, the number was rounded down instead, so correct for that
            if ndigits:
                # use the type of number provided, e.g. float, decimal, fraction
                Numerical = type(number)
                # add the digit 1 in the correct decimal place
                result += Numerical(10) ** -ndigits
                # may need to be tweaked slightly if the addition was inexact
                result = round(result, ndigits)
            else:
                result += 1 # same as 10 ** -0 for precision of zero digits
        return result
    
    assert round_up(0.022499999999999999, 2) == 0.03
    assert round_up(0.1111111111111000, 2) == 0.12
    
    assert round_up(1.11, 2) == 1.11
    assert round_up(1e308, 2) == 1e308
    

提交回复
热议问题