Home > Software engineering >  How to round up a decimal properly in python(or django)
How to round up a decimal properly in python(or django)

Time:12-28

I was trying to round UP a decimal with the code I found below, but it doesn't seem to work properly in python(django). Here is the code:

import math
def round_up(n, decimals=0):
    multiplier = 10 ** decimals
    return math.ceil(n * multiplier) / multiplier

Here are some of the results I get when I run the function:

print(round_up(20.232, 2))
print(round_up(20.211, 2))
print(round_up(20.4, 2))

20.24
20.22
20.4

However, for some reason, I get a weird value when I input 80.4. I am getting 80.41 instead of 80.4:

print(round_up(80.4, 2))
80.41

Is there any other way I can round up decimals in python(django)? I have gotten this off the internet, so there might be some other problems other than the one I mentioned above(inputting 80.4). Basically, I just want to round up a decimal to the second decimal point like above(but of course rounding up 80.4 or 20.3 would just be 80.4 and 20.3 respectively). Thank you, and please leave any questions you have.

CodePudding user response:

The problem occurs when you multiply float numbers

>>> 80.4 * 100
8040.000000000001

So, math.ceil(80.4 * 100) == 8041

If you wanna be precise, you could use Decimal

from decimal import Decimal, ROUND_CEILING

def round_up_decimal(n, decimals=0):
    multiplier = Decimal(10 ** decimals)
    return (n * multiplier).to_integral(rounding=ROUND_CEILING) / multiplier

print(round_up_decimal(Decimal("20.232"), 2))
print(round_up_decimal(Decimal("20.0"), 2))
print(round_up_decimal(Decimal("20.4"), 2))

print(round_up_decimal(Decimal("80.4"), 2))

Output

20.24
20
20.4
80.4

Also, you can create another function to work with float

def round_up_float(n, decimals=0):
    return float(round_up_decimal(Decimal(str(n)), decimals)) # uses previous function


print(round_up_float(Decimal("20.232"), 2))
print(round_up_float(Decimal("20.0"), 2))
print(round_up_float(Decimal("20.4"), 2))

print(round_up_float(Decimal("80.4"), 2))

Output

20.24
20.0
20.4
80.4

CodePudding user response:

I may have misunderstood your question, but as far as I understand, I wanted to write it in case it helps.


Have you tried the round() function already available in Python?

round(20.232, 2)
round(20.0, 2)
round(20.4, 2)
round(80.4, 2)

20.23
20.0
20.4
80.4

I say it again, I answered as far as I understand, of course, this is a ready-made function and it may not be what you want, but if it helps, I would be glad.

  • Related