简体   繁体   English

无法将浮点数转换为十进制数。 首先将float转换为字符串

[英]Cannot convert float to Decimal. First convert float to a string

I get the following error:我收到以下错误:

02/08 09:15:45> Decimal price: 0.00 02/08 09:15:45> 十进制价格:0.00

02/08 09:15:45> Decimal price = None 02/08 09:15:45> 十进制价格 = 无

TypeError: Cannot convert float to Decimal.类型错误:无法将浮点数转换为十进制数。 First convert the float to a string首先将浮点数转换为字符串

Here is my code:这是我的代码:

            s.price = Decimal("%.2f" % (float(request.data['subscription_price'])))
            log('Decimal price: %s' % s.price)
            
            if s.price == Decimal("0.00"):
                s.price = None
                log('Decimal price = None')

Any ideas about what I am doing wrong?关于我做错了什么的任何想法? I tried a hack to avoid saving a 0.00 in the database via the "if s.price == Decimal("0.00"):" ... to no avail.我试图通过“if s.price == Decimal("0.00"):” 避免在数据库中保存 0.00 的 hack 方法,但无济于事。

If you want to convert float number to Decimal with two decimal places this is working code:如果要将浮点数转换为带两位小数的小数,这是工作代码:

import Decimal
In [10]: a = 7.3656
In [11]: Decimal(a).quantize(Decimal('.01'))
Out[11]: Decimal('7.37')

More info about working with decimal numbers you can find here: http://docs.python.org/2/library/decimal.html有关使用十进制数的更多信息,您可以在这里找到: http : //docs.python.org/2/library/decimal.html

if str(s.price) == str(Decimal("0.00")):
   s.price = None
   log('Decimal price = None')

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

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