Number multipleOf Validation in JSON Schema
Use the multipleOf keyword in JSON Schema to constrain numbers to specific increments. Validate currency precision, rotation angles, and batch sizes.
JSON Schema
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"type": "object",
"properties": {
"price": {
"type": "number",
"multipleOf": 0.01,
"minimum": 0
},
"angle": {
"type": "number",
"multipleOf": 90,
"minimum": 0,
"maximum": 360
},
"batchSize": {
"type": "integer",
"multipleOf": 10,
"minimum": 10,
"maximum": 1000
}
},
"required": ["price"]
}Test Data
{
"price": 19.99,
"angle": 270,
"batchSize": 50
}Detailed Explanation
The multipleOf Keyword
The multipleOf keyword constrains a number to be an exact multiple of a given value. This is useful for enforcing decimal precision, step increments, and divisibility rules.
Basic Syntax
{
"type": "number",
"multipleOf": 0.01
}
This ensures the number has at most two decimal places. Values like 19.99, 100, and 0.5 pass, but 19.999 fails because it is not a multiple of 0.01.
How the Example Schema Works
The schema demonstrates three practical uses of multipleOf:
price—multipleOf: 0.01restricts values to two decimal places, matching standard currency precision. The value19.99passes (19.99 / 0.01 = 1999, a whole number). A value like19.995would fail.angle—multipleOf: 90withminimum: 0andmaximum: 360accepts only right-angle rotations: 0, 90, 180, 270, and 360. The value270passes.batchSize—multipleOf: 10ensures batch sizes come in multiples of ten: 10, 20, 30, etc. Combined withminimum: 10andmaximum: 1000, the valid values range from 10 to 1000 in steps of 10. The value50passes.
Floating-Point Precision Warning
Because JSON numbers use IEEE 754 double-precision, multipleOf can produce unexpected results with certain decimal values. For example:
0.1 + 0.2 = 0.30000000000000004 (in IEEE 754)
Most well-implemented validators handle this by comparing with an epsilon tolerance, but some do not. When using multipleOf with decimal fractions, test your specific validator to confirm its behavior.
Common Patterns
| Use case | multipleOf value | Effect |
|---|---|---|
| Currency (2 decimal places) | 0.01 |
Rejects 9.999 |
| Whole numbers | 1 |
Same as type: "integer" |
| Even numbers | 2 |
Accepts 2, 4, 6, ... |
| Quarter hours | 15 |
Accepts 0, 15, 30, 45 |
| Percentage points | 0.1 |
One decimal place |
Combining with Range Constraints
Always combine multipleOf with minimum and/or maximum to fully constrain the value space. Without range limits, multipleOf: 10 accepts any multiple of 10, including negative values and extremely large numbers.
Use Case
Use multipleOf for pricing fields in e-commerce APIs, rotation and positioning values in graphics applications, batch size parameters in data processing endpoints, and time interval settings. It ensures values align with your application's precision requirements.