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.
Round() Round() is a built-in function available with python. It will return you a float number that will be rounded to the decimal places which are given as input. If the decimal places to be rounded are not specified, it is considered as 0, and it will round to the nearest integer.
5 is round up for positive values and round down for negative values. For instance, both round(0.5) and round(-0.5) return 0 , while round(1.5) gives 2 and round(-1.5) gives -2 . This Python behaviour is a bit different from how rounding usually goes.
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)
.
from math import ceil num = 0.1111111111000 num = ceil(num * 100) / 100.0
See:math.ceil
documentationround
documentation - You'll probably want to check this out anyway for future reference
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With