Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Price Validation for Rails 4

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!

like image 453
A. Singla Avatar asked Jul 22 '16 01:07

A. Singla


3 Answers

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.

like image 163
M. Karim Avatar answered Sep 20 '22 11:09

M. Karim


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

like image 43
nikkypx Avatar answered Sep 20 '22 11:09

nikkypx


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.

like image 29
Rich Seviora Avatar answered Sep 21 '22 11:09

Rich Seviora