Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Storing a percentage in Rails + MySQL

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.

like image 627
Chad M Avatar asked Nov 20 '11 17:11

Chad M


People also ask

How do you store percentages in a database?

You should use decimal(p,s) in 99.9% of cases. Percent is only a presentation concept: 10% is still 0.1. Simply choose precision and scale for the highest expected values/desired decimal places when expressed as real numbers. You can have p = s for values < 100% and simply decide based on decimal places.

What data type should you use to store a percentage?

decimal(p,s) / float(n) / real – Are used to store decimal numbers. We can expect that most numerical values we want to store are actually decimal values – percentage, graphical coordinates, sports results etc. bit – Uses only 1 bit to store value 0 or 1 (NULL if not defined).


1 Answers

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.

like image 125
Larry K Avatar answered Sep 26 '22 10:09

Larry K