defining a numeric type that allows up to 2 decimal places

4,313 views
Skip to first unread message

Donal Murtagh

unread,
Nov 30, 2016, 6:52:44 AM11/30/16
to JSON Schema

I'm trying to define a JSON schema for a property


money: 12.12


My main concern is that a maximum of 2 decimal places should be allowed. My initial attempt at defining this field was


money: {
  type
: 'number',
  minimum
: 0,
  multipleOf
: 0.01
}


However, owing to floating point imprecision this fails. For example, using the tv4 validator, the number 147.41 passes validation, but 147.42 fails.

Is there an alternative way to define a numeric type which will only allow a maximum of 2 decimal places?


It seems that the purpose of the "format" attribute is to implement these types of restrictions, but if I define the field like so:


money: {
  type
: 'number',
  format
: 'currency',
  minimum
: 0
}


Then how do I specify that fields with a 'currency' format should only allow up to 2 decimal places?


Thanks in advance.




Henry Andrews

unread,
Nov 30, 2016, 12:59:03 PM11/30/16
to JSON Schema

Austin William Wright

unread,
Jan 3, 2017, 10:25:53 AM1/3/17
to JSON Schema
"multipleOf" is the correct keyword to be using for this case, the problem you're running into is a a limitation of the validator trying to validate a 64-bit IEEE floating point (as parsed by JSON.parse) instead of validating the original JSON document. JSON Schema is only defined over a text JSON document.

However, I would consider dropping this keyword altogether, as it varies currency by currency, and even for US Dollars sometimes you need to deal in fractions of a cent.

Austin.
Reply all
Reply to author
Forward
0 new messages