首页 > 解决方案 > 我希望随机数显示为小数点后 2 位,即使它以整数形式出现

问题描述

我生成了一个随机数,然后我使用 round 将其保留到小数点后 2 位。

有时我会得到一个整数,例如“2”,我希望它显示为“2.00”

或者当我将“3.1”显示为“3.10”时

我尝试使用 round() 舍入到 2 dp

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

没有错误消息只是将一些数字返回到整数或一个 dp

标签: pythondecimalrounding

解决方案


您可以使用格式字符串显式控制输出格式:

print('%.2f' % temp_var_4)

推荐阅读