定义JSON模式货币类型

时间:2022-11-25 16:35:50

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

我正在尝试为属性定义JSON模式

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

我主要担心的是,最多允许2位小数。我最初尝试定义这个领域是

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?

然而,由于浮点不精确,这失败了。例如,使用tv4验证器,数字147.41通过验证,但147.42失败。有没有另一种方法来定义一个只允许最多2位小数的数字类型?

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

似乎“format”属性的目的是实现这些类型的限制,但是如果我像这样定义字段:

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?

那么如何指定具有“货币”格式的字段应该只允许最多2位小数?

1 个解决方案

#1


1  

Your best option is likely to multiply your currency values by 100. Then you have whole numbers, and validation should work fine. In general, using floating point to store monetary values is a bug farm, so you're better off moving toward "integers" even if technically they are still floating point values in JSON.

您最好的选择可能是将您的货币值乘以100.然后您有整数,验证应该可以正常工作。通常,使用浮点来存储货币值是一个错误场,因此即使技术上它们仍然是JSON中的浮点值,您最好转向“整数”。

Some systems use an ISO currency code with the third letter in lower case to denote such currencies. For example GBp for British pence, or USd for US pennies. See https://*.com/a/30635729/4323

某些系统使用ISO货币代码,小写的第三个字母表示此类货币。例如GBp代表英国便士,或USd代表美国便士。请参阅https://*.com/a/30635729/4323

#1


1  

Your best option is likely to multiply your currency values by 100. Then you have whole numbers, and validation should work fine. In general, using floating point to store monetary values is a bug farm, so you're better off moving toward "integers" even if technically they are still floating point values in JSON.

您最好的选择可能是将您的货币值乘以100.然后您有整数,验证应该可以正常工作。通常,使用浮点来存储货币值是一个错误场,因此即使技术上它们仍然是JSON中的浮点值,您最好转向“整数”。

Some systems use an ISO currency code with the third letter in lower case to denote such currencies. For example GBp for British pence, or USd for US pennies. See https://*.com/a/30635729/4323

某些系统使用ISO货币代码,小写的第三个字母表示此类货币。例如GBp代表英国便士,或USd代表美国便士。请参阅https://*.com/a/30635729/4323