python - 我希望随机数显示为小数点后 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
解决方案
您可以使用格式字符串显式控制输出格式:
print('%.2f' % temp_var_4)
推荐阅读
- c# - 如何从 API 反序列化这个 JSON 字符串(数组数组)
- vue.js - Router-View 标记不使用 beforeEach() 显示内容
- python-2.7 - Python 2.7 读取文本文件中的每一行直到字符
- java - 在图像顶部在android中绘制一条丝带
- python - 将字符(或对象)变量转换为数字(或日期时间)变量
- python-3.x - 使用 ywunbiased 时,statsmodels.tsa.stattools 中的 PACF 函数给出大于 1 的数字?
- swift - 为什么遵守 Strideable 会改变乘法的评估方式?
- swift - 在 catch 中引用 do 块中的变量
- elasticsearch - filebeat - Ubuntu 18.04 上的权限被拒绝错误
- sql - 错误报告 - ORA-02253:此处不允许约束规范