Python Decimal too many digits

857 Views Asked by At

I tried creating a temperature converter below:

from decimal import *
getcontext().prec = 10

celsius = Decimal(12)
fahrenheit = celsius*9/5+32
kelvin = celsius+Decimal(273.15)
romer = celsius*21/40+Decimal(7.5)

When converted to a string, fahrenheit returns 53.6 and romer returns 13.8, both with no additional decimal places. However, kelvin returns 285.1500000. (This isn't even 285.1500001). How do I make sure it returns just enough places, i.e. 285.15? I assume it is not a problem with adding floating decimals because romer is fine.

3

There are 3 best solutions below

1
Cameron Wise On

You might be able to use str.format(). For example:

formatted_kelvin = "{:.2f}". format(kelvin)

So, if you printed this, it would print only 2 decimal places.

0
CPMaurya On

Do simple

from decimal import *
getcontext().prec = 10

celsius = Decimal(12)
fahrenheit = celsius*9/5+32
kelvin = round(celsius+Decimal(273.15), 2) #if you need more then 2 digit replace 2 with other number
romer = celsius*21/40+Decimal(7.5)
0
DivyashC On

To make it simple, you can use the built in round() function. It takes in two params, the number required to be rounded and the number of decimals to be rounded.

kelvin = round(celsius+Decimal(273.15), 2)

Here 285.1500000 will be rounded to 2 decimal place 285.15. Other method like str.format(), trunc(), round_up(), etc are also available.