python - Python中可以使用变量来定义小数位吗

标签 python floating-point

我熟悉使用 %.2f 为 float 设置两位小数的约定,但是是否可以通过任何方式将数字更改为变量以便用户可以声明显示的小数位数?

最佳答案

.format是一种更好、更易读的处理变量格式的方法:

'{:.{prec}f}'.format(26.034, prec=3)

关于python - Python中可以使用变量来定义小数位吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15728321/

相关文章:

Python 请求返回 200 而不是 301

c++ - 如何在 C++ 中将字符串转换为具有 6 位精度的 double ?

c++ - 为什么 float 取 0.699999 而不是 0.7

python - 如何检查是否可以在 Python 对象中设置(修补)属性

python - 如何将 python pandas.Dataframe 对象作为参数传递给 celery 任务?

c++ - 可靠地使用 double 作为 std::map 键

c++ - 将精确表示分配给浮点值

c - 为什么 math.h 中的 cos 函数比 x86 fcos 指令更快

python - 使用 pandas.Series.asof : can't compare datetime. 日期时间到 str 时出错

python - ImageData 生成器中的 validation_split 返回 0 个图像