Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Round up to Second Decimal Place in Python

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.

like image 892
user1202589 Avatar asked Feb 10 '12 17:02

user1202589


People also ask

How do you round decimal places in Python?

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.

Does Python round 0.5 up or down?

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.


2 Answers

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

like image 141
simchona Avatar answered Sep 29 '22 00:09

simchona


from math import ceil  num = 0.1111111111000 num = ceil(num * 100) / 100.0 

See:
math.ceil documentation
round documentation - You'll probably want to check this out anyway for future reference

like image 27
Edwin Avatar answered Sep 29 '22 00:09

Edwin