四舍五入到小数点后第二位 python

Rounding to the second decimal place in python

我正在为学校编写一个脚本,其中包括将英里转换为公里或将英里转换为公里。但是,我似乎找不到将输出转换为只转到小数点后第二位的正确方法。我如何更好地编写此代码以将 milesToKilometers 和 kilometersToMiles 的输出格式化为仅转到小数点后第二位?我尝试了一些变体,但我似乎无法做到正确。

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()

您可以使用 built-in round 函数将数字四舍五入到小数点后两位。似乎您只需要将其包含在 milesToKilometerskilometers to miles 函数中。

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

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

注意:如果您希望输出保留尾随零,例如2.10,您需要将其转换为字符串,因为数值会省略尾随零。您可以像这样转换为字符串:

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

您也可以使用格式字符串进行格式化,如下所示

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

请记住,这是舍入而不是截断,这可能是也可能不是您想要的。