python : 将 Unicode 转换为十进制精度的浮点数

python : converting Unicode to float with decimal precision

我想将 unicode 字符串转换为带 2 位小数的浮点数。我正在使用 locale.atof() 来隐藏浮动。我知道我们可以使用 locale.format 将结果值格式化为 2 个小数点。是否可以使用单个函数将 unicode 转换为指定小数精度的浮点数?

目前我是这样使用的

float(locale.format('%.2f',(locale.atof('3.145678'))) 

还有其他方法吗?

float(("%.2f"%float('3.145')))

定义你自己的一个函数:

def trim_decimal_points(s):
    result = float(s)
    return format(result, '.2f')

然后作为一个函数使用:

trim_decimal_points('3.145677777')

您应该考虑 decimal 模块,它提供了处理浮点精度的实用程序,例如:

from decimal import Decimal as D
from decimal import ROUND_DOWN

d = D('3.145677777').quantize(D('0.01'))  
print(d)
# 3.15

如果要截断,也可以设置舍入行为:

d = D('3.145677777').quantize(D('0.01'), rounding=ROUND_DOWN)
print(d)
# 3.14

内置的round函数四舍五入到指定的位数,但是没有一个函数既转换字符串又四舍五入。

>>> round(float('3.141592'),2)
3.14