[Django]-Django decimal form field not taking value equal to max_value

5👍

Floats, like 99.99, are stored in binary. Many numbers that can be represented with finite decimal digits are repeating fractions in binary (see many other questions for that).

In particular, the literal 99.99 is closer to:

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

Python also has Decimals:

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

And sure enough, the Decimal 99.99 is larger than the float max_value 99.99:

>>> d <= 99.99
False

The Django developers knew about binary and this is the entire reason for the existence of the DecimalField: it stores Decimals.

Conclusion: Use Decimal("99.99") as your max_value, not a float.

Leave a comment