You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
When defining a schema like this: { "$schema": "http://json-schema.org/draft-04/schema#", "id": "https://example.com/multipleOf", "type": "object", "properties": { "myNumber": { "type": "number", "multipleOf": 0.1 } }, "required": [ "myNumber" ] }
And a test like this: func TestExampleJson_UnmarshalJSON(t *testing.T) { json :={"myNumber": 148.1}`
a := ExampleJson{}
err := a.UnmarshalJSON([]byte(json))
assert.NoError(t, err)
}
`
The decoding fails with an error. That is due to math.Abs(math.Mod(plain.MyNumber, 0.1)) returning 0.0999999999999861 instead of something lower than 1e-10.
The decoding code should not be: if math.Abs(math.Mod(plain.MyNumber, 0.1)) > 1e-10 { return fmt.Errorf("field %s: must be a multiple of %v", "myNumber", 0.100000) }
but instead be: { remainder := math.Mod(plain.MyNumber, 0.1) if !(math.Abs(remainder) < 1e-10 || math.Abs(remainder-0.1) < 1e-10) { return fmt.Errorf("field %s: must be a multiple of %v", "myNumber", 0.100000) } }
The text was updated successfully, but these errors were encountered:
deep-creek
changed the title
multipleOf doesn't work for bigger values due to precision
multipleOf doesn't work for smaller multiples due to precision
Feb 17, 2025
When defining a schema like this:
{ "$schema": "http://json-schema.org/draft-04/schema#", "id": "https://example.com/multipleOf", "type": "object", "properties": { "myNumber": { "type": "number", "multipleOf": 0.1 } }, "required": [ "myNumber" ] }
And a test like this:
func TestExampleJson_UnmarshalJSON(t *testing.T) { json :=
{"myNumber": 148.1}`}
`
The decoding fails with an error. That is due to
math.Abs(math.Mod(plain.MyNumber, 0.1))
returning 0.0999999999999861 instead of something lower than 1e-10.The decoding code should not be:
if math.Abs(math.Mod(plain.MyNumber, 0.1)) > 1e-10 { return fmt.Errorf("field %s: must be a multiple of %v", "myNumber", 0.100000) }
but instead be:
{ remainder := math.Mod(plain.MyNumber, 0.1) if !(math.Abs(remainder) < 1e-10 || math.Abs(remainder-0.1) < 1e-10) { return fmt.Errorf("field %s: must be a multiple of %v", "myNumber", 0.100000) } }
The text was updated successfully, but these errors were encountered: