Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/292.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何使用Pyhton中的字符串格式编写程序以打印最多2位小数的浮点数_Python - Fatal编程技术网

Python 如何使用Pyhton中的字符串格式编写程序以打印最多2位小数的浮点数

Python 如何使用Pyhton中的字符串格式编写程序以打印最多2位小数的浮点数,python,Python,我有这个,但它不起作用 number = int(input("Please give the number")) print("Formatted Number: " + "{:.2f}".format(number)); print(number) 此代码出现错误,因为您在输入时试图将浮点值转换为int。如果要从用户处获取浮点输入,然后根据需要对值进行四舍五入,并将其转换为字符串值,则可以使用下面提供的代码: number = float(input("Please give the nu

我有这个,但它不起作用

number = int(input("Please give the number"))
print("Formatted Number: " + "{:.2f}".format(number));
print(number)

此代码出现错误,因为您在输入时试图将浮点值转换为int。如果要从用户处获取浮点输入,然后根据需要对值进行四舍五入,并将其转换为字符串值,则可以使用下面提供的代码:

number = float(input("Please give the number"))  # take input as float

print("Formatted Number: " + str(round(number,2)))  # round upto 2 and convert to string  

请让我知道这是否是您正在寻找的

print("Formatted Number: " + "{:.2f}".format(number));
将起作用,但您无法将int数字四舍五入

number=int中删除“int”(输入(“请给出数字”)

并将其替换为“float”
number=float(输入(“请给出数字”)
代替“int”,您可以使用“eval”


到底是什么不起作用?预期的结果是什么?这回答了你的问题吗?这回答了你的问题吗?
  number = eval(input("Please give the number"))
  print("Formatted Number: " + "{:.2f}".format(number));
  print(number)