简体   繁体   English

我可以将任何字符串转换为float而不会在Python中丢失精度吗?

[英]Can I convert any string to float without losing precision in Python?

I'm parsing some price information from an API, do I need to worry about losing precision if I just do price = float(price_str) ? 我正在从API中解析一些价格信息,如果我只做price = float(price_str) ,我是否需要担心失去精度?

Or do I have to use decimal.Decimal to make sure the original value is parsed? 或者我是否必须使用decimal.Decimal来确保解析原始值?

Use Decimal class when working with currency! 使用货币时使用十进制类! Why? 为什么? Let's see this dummy example: 让我们看看这个虚拟的例子:

float('0.2') + float('0.1')

Result: 0.30000000000000004 结果: 0.30000000000000004

With Decimal instead: 用十进制代替:

Decimal('0.2') + Decimal('0.1')

Result: Decimal('0.3') 结果: Decimal('0.3')

UPDATE: 更新:

if you are using third party API with json format, you can use Decimal to automatically parse floating numbers automatically: see my blog post: http://www.daveoncode.com/2014/10/21/python-reading-numbers-from-json-without-loss-of-precision-using-decimal-class-for-data-processing/ 如果您使用的是带有json格式的第三方API,您可以使用Decimal自动自动解析浮点数:请参阅我的博客文章: http//www.daveoncode.com/2014/10/21/python-reading-numbers-from -json-而不-失精密使用小数级换数据处理/

Prices should be decimal, floats often introduce rounding errors which will give you headaches in the long run. 价格应为十进制,浮点数通常会引入舍入错误,从长远来看会让您头疼。 Example: 例:

In [1]: 3*0.1
Out[1]: 0.30000000000000004

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM