Python浮点数到十进制转换 [英] Python float to Decimal conversion

查看:343
本文介绍了Python浮点数到十进制转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Python Decimal不支持从float构造。它期望您必须先将float转换为字符串。

Python Decimal doesn't support being constructed from float; it expects that you have to convert float to a string first.

这非常不方便,因为float的标准字符串格式器要求您指定小数位数而不是有效位数。因此,如果您的数字最多可以保留15个小数位,则需要将其格式设置为Decimal(%。15f%my_float),如果您之前还有任何有效数字,也将在第15个小数位处产生垃圾

This is very inconvenient since standard string formatters for float require that you specify number of decimal places rather than significant places. So if you have a number that could have as many as 15 decimal places you need to format as Decimal(""%.15f"% my_float), which will give you garbage at the 15th decimal place if you also have any significant digits before decimal.

有人可以建议一种在用户输入时从float转换为Decimal保留值的好方法吗,也许会限制可以支持的有效位数?

Can someone suggest a good way to convert from float to Decimal preserving value as the user has entered, perhaps limiting number of significant digits that can be supported?

推荐答案

Python< 2.7



Python <2.7

"%.15g" % f

或者在Python 3.0中:

Or in Python 3.0:

format(f, ".15g")



Python 2.7 +,3.2 +



只需将浮点数直接传递给 Decimal 构造函数,如下所示:

Python 2.7+, 3.2+

Just pass the float to Decimal constructor directly, like this:

from decimal import Decimal
Decimal(f)

这篇关于Python浮点数到十进制转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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