MeltedKendal
MeltedKendal

Reputation: 69

How to round floats to 1st decimal place?

For a class I am to write a program that converts Fahrenheit to Celsius and visa versa. The result should be rounded to the first decimal place. I have tried the "round" function in a number of ways without success.

temp=float(input("Enter a temperature value to convert: "))
unit=str(input("Convert to Fahrenheit or Celsius? Enter f or c: "))

if unit=="c" or unit == "C":
    degC=(temp)
    temp= (1.8*temp)+32
    print(str(temp) + " degrees fahrenheit = " + str(degC) + " degrees Celsius. ")
if unit=="f" or unit == "F":
    degF=(temp)
    temp= (temp-32)/1.8
    print(str(temp)+ " degrees celsius = " + str(degF) + " degrees Fahrenheit. ")
else:
    print("you did not enter an f or c. Goodbye ")

Upvotes: 1

Views: 698

Answers (2)

Marvin
Marvin

Reputation: 3025

One of the nice features of python is that a python shell lets you explore everything you don't understand.

$ python
Python 3.4.2 (v3.4.2:ab2c023a9432, Oct  5 2014, 20:42:22) 
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> print( round(3.1415,3),  round(3.1415,2),  round(3.1415,1),  round(3.1415,0))
3.142 3.14 3.1 3.0
>>> help(round)
<various help is printed>

Often you can test lots of little bits of your code to see if your understanding matches what the actual behavior is. From my example, I think you can see the behavior of round(), and perhaps your real problem is elsewhere.

Upvotes: 1

Moshe Slavin
Moshe Slavin

Reputation: 5214

You can use the round(number, 1) built-in function!

For example:

>>> round(45.32345, 1)

45.3

In your case:

temp=float(input("Enter a temperature value to convert: "))
unit=str(input("Convert to Fahrenheit or Celsius? Enter f or c: "))

if unit=="c" or unit == "C":
    degC=(temp)
    temp= (1.8*temp)+32
    print(str(round(temp), 1) + " degrees fahrenheit = " + str(degC) + " degrees Celsius. ")
el*emphasized text*if unit=="f" or unit == "F":
    degF=(temp)
    temp= (temp-32)/1.8
    print(str(round(temp), 1)+ " degrees celsius = " + str(degF) + " degrees Fahrenheit. ")
else:
    print("you did not enter an f or c. Goodbye ")

What python actually does is something like:

def truncate(n, decimals=0):
    multiplier = 10 ** decimals
    return int(n * multiplier) / multiplier

You can read more about python-rounding

Hope this helps!

Upvotes: 1

Related Questions