Round up to Second Decimal Place in Python

user1202589 picture user1202589 · Feb 10, 2012 · Viewed 120k times · Source

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

0.022499999999999999

Should round up to 0.03

0.1111111111111000

Should round up to 0.12

If there is any value in the third decimal place, I want it to always round up leaving me 2 values behind the decimal point.

Answer

simchona picture simchona · Feb 10, 2012

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).