Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 十进制(0.19)结果是非常长的数字?_Python_Django - Fatal编程技术网

Python 十进制(0.19)结果是非常长的数字?

Python 十进制(0.19)结果是非常长的数字?,python,django,Python,Django,我的模型: class Product(models.Model): VAT_CHOICES = [ (Decimal(0.19), Decimal(0.19)), (Decimal(0.07), Decimal(0.07)), ] vat = models.DecimalField( choices=VAT_CHOICES, max_digits=12, decimal_places=2,

我的模型:

class Product(models.Model):
    VAT_CHOICES = [
        (Decimal(0.19), Decimal(0.19)),
        (Decimal(0.07), Decimal(0.07)),
    ]
    vat = models.DecimalField(
        choices=VAT_CHOICES,
        max_digits=12,
        decimal_places=2,
        default=Decimal(0.19))
0.19
解析为
decimal
数字会产生一个非常长的数字,大约有20位小数。我做错了什么?避免这种情况的最佳方法是什么


我总是要写e吗。g<代码>四舍五入(十进制(0.19),2)以获得所需的数字?我想要精确的数字
0.19

正如前面的评论所指出的,您应该使用
str
而不是
float
作为
十进制
构造函数的参数;发生错误的原因是
0.19
0.07
无法无损转换为小数点后两位的定点表示。请阅读中的更多内容,特别是其中将
浮点
解释为
十进制
的参数

因此,您的模型可以如下所示:

class Product(models.Model):
    VAT_CHOICES = [
        (Decimal('0.19'), Decimal('0.19')),
        (Decimal('0.07'), Decimal('0.07')),
    ]
    vat = models.DecimalField(
        choices=VAT_CHOICES,
        max_digits=12,
        decimal_places=2,
        default=VAT_CHOICES[0][0])

我还使用了
VAT\u选项
作为
default
关键字,以减少冗余。

尝试
Decimal(“0.19”)
。你没做错什么,这只是一个普通的浮点精度问题。是的,我看到了。。。但我不知道如何处理这件事。。。将小数位数增加到一个非常高的数字的解决方案是什么?改用浮动字段?我还想对用户生成的数字进行一些算术运算,这些数字将从JSON中解析出来。您应该在这里使用字符串,因为使用
Decimal(0.19)
将浮点数作为初始值,因此已经引入了错误。