使用新的 Python 格式函数舍入小数 [英] Rounding decimals with new Python format function
问题描述
如何使用 Python 3.0 format
函数将小数四舍五入到特定的小数位数?
这是一个典型的、有用的例子...:
<预><代码>>>>n = 4>>>p = 数学.pi>>>'{0:.{1}f}'.format(p, n)'3.1416'嵌套的 {1}
接受第二个参数,即 n 的当前值,并按照指定的方式应用它(这里是格式的精度"部分——小数点),然后应用外部结果 {0:.4f}
.当然,如果您愿意,您可以对 4
(或任何数字)进行硬编码,但关键是,您不必必须!
更好...:
<预><代码>>>>'{number:.{digits}f}'.format(number=p,digits=n)'3.1416'...代替上面的 0 和 1 等模糊的参数编号",您可以选择使用闪亮清晰的参数 names,并将相应的值作为 keyword(又名named")format
的参数——这可以所以更具可读性,如您所见!!!
How do I round a decimal to a particular number of decimal places using the Python 3.0 format
function?
Here's a typical, useful example...:
>>> n = 4
>>> p = math.pi
>>> '{0:.{1}f}'.format(p, n)
'3.1416'
the nested {1}
takes the second argument, the current value of n, and applies it as specified (here, to the "precision" part of the format -- number of digits after the decimal point), and the outer resulting {0:.4f}
then applies. Of course, you can hardcode the 4
(or whatever number of digits) if you wish, but the key point is, you don't have to!
Even better...:
>>> '{number:.{digits}f}'.format(number=p, digits=n)
'3.1416'
...instead of the murky "argument numbers" such as 0 and 1 above, you can choose to use shiny-clear argument names, and pass the corresponding values as keyword (aka "named") arguments to format
-- that can be so much more readable, as you see!!!
这篇关于使用新的 Python 格式函数舍入小数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!