1

I'm trying to figure out how to show only one digit after the decimal point in a Celsius to Fahrenheit conversion assignment. The only one coming up with multiple digits thus far is 13 degrees Celsius, which ends up as 55.400000000000006. My for statement looks like this.

def main():
    for ct in range (0, 21):
        fe = 9 / 5 * (ct) + 32
        print (ct, "Celsius equals", fe, "Fahrenheit")

Like I said, the program runs as expected, I just would like to clean that one conversion up.

Amadan
  • 191,408
  • 23
  • 240
  • 301

5 Answers5

1
print("%d Celsius equals %.1f Fahrenheit" % (ct, fe))
# => 13 Celsius equals 55.4 Fahrenheit
Amadan
  • 191,408
  • 23
  • 240
  • 301
0

You can use the python function round().

https://docs.python.org/2/library/functions.html#round

I believe the proper usage would be round(fe, 1).

Jeremy
  • 394
  • 4
  • 13
0

It looks like you might be using Python. To format your code, put four blank spaces before each line so that it is more readable, like this:

def main(): 
    for ct in range (0, 21): 
        fe = 9 / 5 * (ct) + 32 
        print (ct, "Celsius equals", fe, "Fahrenheit")

If you want to round your answer, use Python's round() function. This would make your print statement something like this: print (ct, "Celsius equals", round(fe, 1), "Fahrenheit")

0
import math
def main():
    for ct in range (0, 21):
        fe = 9 / 5 * (ct) + 32
        print(ct, "Celsius equals", (math.ceil(fe*100)/100) , "Fahrenheit")

This might work.

0

You can show one decimal point without having to use another operator like round or math.ceil. (In python 2.7 this would be)

'%.1f' % (5.34)

Here are some quirks of using the round function that you should be aware of : round() in Python doesn't seem to be rounding properly

Community
  • 1
  • 1
fixxxer
  • 15,568
  • 15
  • 58
  • 76