Round up to Second Decimal Place in Python

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

    Python includes the round() function which lets you specify the number of digits you want. From the documentation:

    round(x[, n])

    Return the floating point value x rounded to n digits after the decimal point. If n is omitted, it defaults to zero. The result is a floating point number. Values are rounded to the closest multiple of 10 to the power minus n; if two multiples are equally close, rounding is done away from 0 (so. for example, round(0.5) is 1.0 and round(-0.5) is -1.0).

    So you would want to use round(x, 2) to do normal rounding. To ensure that the number is always rounded up you would need to use the ceil(x) function. Similarly, to round down use floor(x).

提交回复
热议问题