-1

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.

John
  • 87
  • 4
  • 1
    What is `precision`? Make this a running script including the print showing the output. – tdelaney Feb 25 '22 at 00:27
  • 2
    `Decimal(273.15)` doesn't mean what you think it means. – user2357112 Feb 25 '22 at 00:39
  • You should initialize `Decimal` with strings (e.g., `Decimal("273.15")`) and avoid doing floating point math with python integers (`9/5` should be `Decimal("9")/Decimal("5")`), etc... But mostly, you should make this a fully running example, including display of the result, and let us know whats wrong. Note, this is what I asked 2 hours ago. Lets make this a good question! – tdelaney Feb 25 '22 at 02:45

3 Answers3

0

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)
CPMaurya
  • 371
  • 3
  • 9
0

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.

DivyashC
  • 41
  • 4
-1

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.

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
  • Thanks! However, it wouldn't work properly if the actual answer contains more decimal places. – John Feb 25 '22 at 07:03