0

I am writing a script for school that consists of converting either miles to kilometers or vis versa. However, I can't seem to find the proper way to convert the output to only go to the second decimal place. How would I write this code better to format the output of milesToKilometers and kilometersToMiles to only go to the second decimal place? I have tried a few variations but I can't seem to get it correct.

def main():
    # Declare local variables
    miles = 0
    kilometers = 0
    convert = ""

    # Get user input
    convert = str(input("Would you like to convert miles to kilometers or kilometers to miles?"))

    # If / Else Statement
    if convert == "miles to kilometers":
        miles = int(input("How many miles do you want to convert to kilometers?"))
        milesOutput = milesToKilometers(miles)
        print(miles ,"miles converted to kilometers is", milesOutput)
    elif convert == "kilometers to miles":
        kilometers = int(input("How many kilometers do you want to convert to miles?"))
        kilometerOutput = kilometersToMiles
        print(kilometers, "kilometers convert to miles is", kilometerOutput)
    else:
        print("Invalid Input. Restart to try again.")

def milesToKilometers(miles):
    mileConverstion = miles * 1.60934
    return mileConverstion

def kilometersToMiles(kilometers):
    kilometerConverstion = kilometers * 0.621371
    return kilometerConverstion

# Start Program
main()
rcshon
  • 907
  • 1
  • 7
  • 12
  • 1
    you can use `round(some_number, 2)` – rcshon Apr 17 '22 at 04:24
  • @rcshon this is not what OP wants, and is almost never the solution in general. Floating-point numbers don't *have* decimal digits, so mathematically trying to approximate a decimal number doesn't always give something that will print nicely. Please see https://0.30000000000000004.com/ and https://stackoverflow.com/questions/588004/. – Karl Knechtel Apr 17 '22 at 04:41

2 Answers2

0

You can use the built-in round function to round a number to up to 2 decimal places. Seems like you only need to include this in the milesToKilometers and kilometers to miles functions.

def milesToKilometers(miles):
    mileConverstion = miles * 1.60934
    return round(mileConverstion, 2)

def kilometersToMiles(kilometers):
    kilometerConverstion = kilometers * 0.621371
    return round(kilometerConverstion, 2)

Note: If you want the output to keep the trailing zeros e.g. 2.10, you need to convert it into a string as numerical values omit trailing zeros. You can convert to a string like this:

with_decimals = f'{round(number, 2):.2f}'

rcshon
  • 907
  • 1
  • 7
  • 12
0

You can also do the formatting by using format strings as follows

miles = 3.1415
print(f'{miles:.1f}') # 1 decimal places
print(f'{miles:.2f}') # 2 decimal places
# and so on

Keep in mind that this is rounding and not truncating which may or may not be what you want.