python - 将 float 舍入为 x 位小数?

标签 python math rounding

有没有办法将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/

相关文章:

Python:未安装 _imagingft C 模块

javascript - 在 JavaScript Math.Floor((Math.Random() * 1) + 0) 中得到 1 的概率

C# 科学计算 - 大数小数位数

python - 舍入系统 RAM 和 HDD 字节,向上到最接近的千兆字节。 Python

python - 我可以从之前运行的 python 脚本中读取代码吗

python - Pyspark - 获取使用 ParamGridBuilder 创建的模型的所有参数

math - 在Mathematica中绘制量子谐波振荡器

c++ - fmod 告诉我 1 的小数部分是 1

internet-explorer - IE 中的边框半径不起作用

python - Python 3.1 http 服务器的快速问题