Storing a percentage in Rails + MySQL

mysql, ruby-on-rails

Solution

Your first thought is the right one...don't overthink it.

You should definitely store percentage numbers in the database in hundredths format. And use that format in all of your Ruby calculations.

Percentage figures are a display convention. Eg the number 0.45 is displayed as 45%. As such, use a View helper to convert your percentage figures from their internal format (decimal numbers) to your chosen display format--a string which includes the % sign.

Problem

I need to use a percentage in my Rails app. In any view, including when it is entered by the user, the format will need to be the hundreds format, `100.000`. When it's used in calculations, it needs to be represented in the hundredths format, `1.00000`. My migration (I'm adding the column to an existing table) has the following line: ``` add_column :worker, :cash_split, :decimal, :precision => 6, :scale => 5 ``` So, as of right now, I'm storing it in the hundredths (`1.00000`) format. My basis for choosing to store it in this format is that i figure it will mean cleaner business logic (i.e. no `worker.cash_split / 100.0.to_d` code hanging around) when i need to do multiplication. My only other thought was maybe abusing the composed_of method. I could store the data in the hundreds (`100.000`) format as cash_split and then make an attribute accessor `cash_split_percentage` that returns `cash_split` in its 1.0000 format counterpart.

Original source