Skip to content

multipleOf doesn't account for rounding errors #222

Description

@lpersin

Hi,

I've encountered a problem with the v1 where the code checking for the multipleOf condition of the json-schema quickly gets thrown off by any rounding error.

Here's how the current code attempts to validate the rule:

  if (schema.multipleOf !== undefined && value % schema.multipleOf !== 0) {
    errors.push({ path, validation: 'multipleOf', schema, value })
  }

But this fails in very simple cases like:

> 100 % 0.01
0.009999999999997919

Other json-schema validation libraries seem to handle this by allowing to pass an arbitrary tolerance, something looking like this could solve this issue
Eg:

if (schema.multipleOf !== undefined) {
    const remainder = value % schema.multipleOf
    const precision = 1e-7
    if (!(Math.abs(remainder) < precision || Math.abs(remainder - schema.multipleOf) < precision)) {
      errors.push({ path, validation: 'multipleOf', schema, value })
    }
  }

I chose an arbitrary default precision here but you get the idea.

I wanted to open a PR with this suggestion but found that ultimately it should be up to the user to pass the desired tolerance when calling createHeadlessForm or handleValidation, yet these functions don't currently allow passing in additional validation options.

I'm not sure what the desired design direction is here, so I'm opening this issue to get some feedback on a potential fix.

Thanks

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions