Rails 4 的价格验证 [英] Price Validation for Rails 4
问题描述
我的 rails 应用程序中有一个 pieces
模型,每个部分都有一个名为 :price
的小数.我想验证这个价格是两位小数,大于 0,并且小于一百万美元.我查看了许多关于堆栈溢出的来源,每当我为这些验证输入小数时,例如 4.99 ,价格就会变成 4.990000000000000213162820728030055761.我查过的所有验证都发生了这种情况.这是因为我需要在我的数据库中指定小数的精度吗?我该如何解决这个问题?
I have a pieces
model in my rails app, and each piece has a decimal called :price
. I want to validate that this price is two decimal places, greater than 0, and is less than a million dollars. I have looked at numerous sources on Stack overflow, and whenever I type a decimal for these validations, for example, 4.99 , the price becomes 4.990000000000000213162820728030055761. This has happened for all the validations I have looked up. Is this because I need to specify my precision for the decimal in my database? How can I fix this?
我目前的验证:
validates :price, :presence => true, :format => { :with => /\A(\$)?(\d+)(\.|,)?\d{0,2}?\z/ }
谢谢各位!
推荐答案
我不知道您使用的是哪个数据库,但您可以像这样在迁移中定义精度,
I dont know which database you are using but you can define precision in your migration like this,
add_column :pieces, :price, :decimal, precision: 8, scale: 2
它会给你总共 8 位数字,小数点后有 2 位.
It will give you a total of 8 digits, with 2 after the decimal point.
关于验证,
如果你希望 :price
应该总是有两位小数(即:4.99),你可以试试这个,
About the validation,
If you want that the :price
should always have two decimal place (i.e: 4.99) you can try this,
validates :price, presence: true, format: { with: /\A\d+(?:\.\d{2})?\z/ }, numericality: { greater_than: 0, less_than: 1000000 }
如果您希望 :price
最多有两位小数或更少(即:4、4.9、4.99),您可以试试这个,
If you want that the :price
should have at most two decimal or less (i.e: 4, 4.9, 4.99) you can try this,
validates :price, presence: true, format: { with: /\A\d+(?:\.\d{0,2})?\z/ }, numericality: { greater_than: 0, less_than: 1000000 }
或者,如果您不想验证精度而只想在将精度四舍五入到数据库之前,您可以使用 round_with_precision.
Or if you dont want to validate precision and just want to round up the precision before you save it to the database you can use round_with_precision.
这篇关于Rails 4 的价格验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!