我希望随机数显示为小数点后两位,即使它是整数
I want when a random number to show as 2 decimal places even if it comes up as an integer
我生成了一个随机数,然后我使用 round 将其保留到小数点后两位。
偶尔我会得到一个整数,例如“2”,我希望它显示为“2.00”
或者当我将“3.1”显示为“3.10”时
我尝试使用 round()
四舍五入到 2 d.p
import random
#this creates a number between 2 and 5.99 by adding a decimal to an integer then rounds the sum to 2 d.p
def second_question():
temp_var_4 = random.randint(2,5) + round(random.random(),2)
print(temp_var_4)
second_question()
没有错误消息,只是将一些数字返回为整数或一个 d.p
您可以使用格式字符串显式控制输出格式:
print('%.2f' % temp_var_4)
我生成了一个随机数,然后我使用 round 将其保留到小数点后两位。
偶尔我会得到一个整数,例如“2”,我希望它显示为“2.00”
或者当我将“3.1”显示为“3.10”时
我尝试使用 round()
四舍五入到 2 d.pimport random
#this creates a number between 2 and 5.99 by adding a decimal to an integer then rounds the sum to 2 d.p
def second_question():
temp_var_4 = random.randint(2,5) + round(random.random(),2)
print(temp_var_4)
second_question()
没有错误消息,只是将一些数字返回为整数或一个 d.p
您可以使用格式字符串显式控制输出格式:
print('%.2f' % temp_var_4)