Django decimal form field not taking value equal to max_value

I have a DecimalField in my form and I would like to constrain min_value=0.1

andmax_value=99.99

purity_percent = forms.DecimalField(max_value=99.99, min_value=0.1, decimal_places=2)

      

But when i try to enter a value equal to 0.1

or 99.99

i wont work i get this error

For 0.1 : Ensure this value is greater than or equal to 0.1.

For 99.99 : Ensure this value is less than or equal to 99.99.

How can I include in the limit too.?

+3


source to share


1 answer


Floats such as 99.99

are stored in binary format. Many numbers that can be represented by trailing decimal digits repeat fractions in binary (see Many other questions for this).

In particular, the letter is 99.99

closer to:

>>> "{:.15f}".format(99.99)
'99.989999999999995'

      

Python also has decimal numbers:

>>> from decimal import Decimal
>>> d = Decimal("99.99")

      



And of course, Decimal 99.99 is larger than float max_value 99.99:

>>> d <= 99.99
False

      

The Django developers knew about binaries, and for good reason DecimalField

: it stores Decimals.

Conclusion: Use Decimal("99.99")

as your max_value, not float.

+3


source







All Articles