Python 中四舍五入到两位小数
在 Python 中,可以使用 round 函数实现小数四舍五入。它接受两个参数:要舍入的数字以及要舍入的精度或小数位数。
要解决您在华氏温度到摄氏温度转换器中遇到的问题,请考虑以下代码片段:
def main(): printC(formeln(typeHere())) def typeHere(): global Fahrenheit try: Fahrenheit = int(input("Hi! Enter Fahrenheit value, and get it in Celsius!\n")) except ValueError: print("\nYour insertion was not a digit!") print("We've put your Fahrenheit value to 50!") Fahrenheit = 50 return Fahrenheit def formeln(c): Celsius = (Fahrenheit - 32.00) * 5.00/9.00 return Celsius def printC(answer): answer = str(round(answer, 2)) # Round to two decimal places print("\nYour Celsius value is " + answer + " C.\n") main()
这里,在 printC 函数中,我们添加 round(answer, 2) 以确保结果四舍五入到小数点后两位。 round 函数返回一个浮点数,因此我们在打印之前将其转换回字符串 (str)。
此修改现在会将所有摄氏值四舍五入到小数点后两位,为您提供更精确的输出。
以上是如何在 Python 中将浮点数四舍五入到小数点后两位?的详细内容。更多信息请关注PHP中文网其他相关文章!