开发者

Python/Django: If 5 and 5.00 are different values (when expressed in Decimal), then

开发者 https://www.devze.com 2022-12-15 20:21 出处:网络
If 5 and 5.00 and 5.000 are all different, then why does Django\'s decimal field sa开发者_如何学Cve without the .00 even when I have decimal_places=2

If 5 and 5.00 and 5.000 are all different, then why does Django's decimal field sa开发者_如何学Cve without the .00 even when I have decimal_places=2

?

More importantly, how can I save a value 5.00 as 5.00 in Django without using String.


I think it would be more correct to say those are different representations of the same value '5'.

Internally, the value saved (unless you're actually storing a string) is 5.

When the value is displayed, ie converted to a string representation for the screen, it might be shown as 5, 5.00 or 5.000 but internally, it's still 5

The two decimal places do not appear (if I can put it that way) until the value is output.

You can't save a number with 2 decimal places unless you use a string.


You have an argument that Django ought to enforce a certain precision on its Python objects, but decimal_places is probably more about maximum precision. I believe precision is not stored in the database, so it will be lost in any case.

In any case, if you want to enforce precision, use something like: Decimal(5).quantize(Decimal(10)**-DECIMAL_PLACES)

You can overload the to_python method in a custom django.db.models.DecimalField to ensure that a python Decimal object with the correct precision is returned.

0

精彩评论

暂无评论...
验证码 换一张
取 消