python-jsonschema / jsonschema

An implementation of the JSON Schema specification for Python
https://python-jsonschema.readthedocs.io
MIT License
4.52k stars 574 forks source link

multipleOf fails to validate that 4.02 is a multiple of 0.01 due to floating point math #1234

Closed 5eb closed 4 months ago

5eb commented 4 months ago

Hi jsonschema fails to validate that 4.02 is a multiple of 0.01 due to floating point math. This is the exact example given in the spec: multiples

Reading the implementation it is easy to see why this is so.

ipython demonstration

This can be solved with either division between Decimal:s or Fraction:s. Probably in other ways as well. Fraction should probably be easiest as that is already your fallback on OverflowError. My suggestion is to check if both dB and instance are floats.

This is causing real world issues in a financial reporting application that requires submissions to be rounded to a specific number of decimal precision (think cents as floating point dollars). In an ideal world floats would of course never be used for amounts, but here we are. I'm a data submitter, not the one who designed the schema.

I understand there might be other corner cases I'm not thinking off. However, the current implementation fails on the single example given in the reference docs of how to use multipleOf with floats, so I think this is a valid complaint.

Julian commented 4 months ago

This is indeed a common request, and totally in your hands to do, if you want decimal or fraction division, deserialize your JSON using decimals or fractions as the json module allows.