可以在Python中使用变量来定义小数位吗 [英] Can a variable be used in Python to define decimal places

查看:102
本文介绍了可以在Python中使用变量来定义小数位吗的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm familiar with the convention of using %.2f to set two decimal places for a float but is it in any way possible to change the number to a variable so that the user can state the number of decimal places displayed?

推荐答案

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

.format is a nicer, more readable way to handle variable formatting:

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

这篇关于可以在Python中使用变量来定义小数位吗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆