'Python Decimal too many digits
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.
Solution 1:[1]
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)
Solution 2:[2]
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.
Solution 3:[3]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | CPMaurya |
| Solution 2 | DivyashC |
| Solution 3 | mkrieger1 |
