有没有办法将python浮点数四舍五入到x个小数?例如:
>>> x = roundfloat(66.66666666666, 4)
66.6667
>>> x = roundfloat(1.29578293, 6)
1.295783
我找到了修剪/截断它们的方法 (66.666666666 --> 66.6666),但不是圆形的 (66.666666666 --> 66.6667)。
最佳答案
使用内置函数 round()
:
In [23]: round(66.66666666666,4)
Out[23]: 66.6667
In [24]: round(1.29578293,6)
Out[24]: 1.295783
round()
帮助:round(number[, ndigits]) -> floating point number
Round a number to a given precision in decimal digits (default 0 digits). This always returns a floating point number. Precision may be negative.
关于python - 将 float 舍入为 x 位小数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13479163/