Price Validation for Rails 4

守給你的承諾、 提交于 2021-02-18 22:35:52

问题


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?

My current validation:

validates :price, :presence => true, :format => { :with => /\A(\$)?(\d+)(\.|,)?\d{0,2}?\z/ }

Thanks guys!


回答1:


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

It will give you a total of 8 digits, with 2 after the decimal point.

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 }

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 }

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.




回答2:


You should set it on the database. For example in a migration:

add_column :products, :price, :decimal, precision: 5, scale: 2

Precision is the number of digits in a number. Scale is the number of digits to the right of the decimal point in a number. For example, the number 123.45 has a precision of 5 and a scale of 2. In SQL Server, the default maximum precision of numeric and decimal data types is 38.

https://msdn.microsoft.com/en-us/library/ms190476.aspx




回答3:


If you're seeing that your values are having additional numbers tacked on, what's likely happening is that your column is set as a floating-point type. If you're working with dollar values do not use floating-point numbers. M. Karim's answer is fine otherwise.



来源:https://stackoverflow.com/questions/38517013/price-validation-for-rails-4

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!