将浮点数舍入为 x 位小数? [英] Round float to x decimals?

查看:37
本文介绍了将浮点数舍入为 x 位小数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法将python浮点数四舍五入为x个小数?例如:

<预><代码>>>>x = 圆浮点数(66.66666666666, 4)66.6667>>>x = roundfloat(1.29578293, 6)1.295783

我找到了修剪/截断它们的方法 (66.666666666 --> 66.6666),但不是圆角 (66.666666666 --> 66.6667).

解决方案

使用内置函数round():

在[23]中:round(66.66666666666,4)出[23]:66.6667在 [24] 中:round(1.29578293,6)出[24]:1.295783

关于round()的帮助:

<块引用>

round(number[, ndigits]) -> 浮点数

将数字四舍五入到给定精度的十进制数字(默认为 0数字).这总是返回一个浮点数.精度可否定.

Is there a way to round a python float to x decimals? For example:

>>> x = roundfloat(66.66666666666, 4)
66.6667
>>> x = roundfloat(1.29578293, 6)
1.295783

I've found ways to trim/truncate them (66.666666666 --> 66.6666), but not round (66.666666666 --> 66.6667).

解决方案

Use the built-in function round():

In [23]: round(66.66666666666,4)
Out[23]: 66.6667

In [24]: round(1.29578293,6)
Out[24]: 1.295783

help on 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.

这篇关于将浮点数舍入为 x 位小数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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