Python浮点数到十进制转换

编程入门 行业动态 更新时间:2024-10-09 20:22:59
本文介绍了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浮点数到十进制转换

本文发布于:2023-05-25 19:52:14,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/236200.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:浮点   数到   Python   十进制

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!