Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store a percentage value?

I am using Rails 3.2.2 and I would like to store and handle a percentage value in a my database table column. What do you advice about (for example, what type - :integer, :float, :decimal, ... - of the column should I set)? Is there some alert that I must/should know about storing percentage values?

The precision should be 2 (1.99%, 50.01%, ...).

Note: I read this post.

like image 381
Backo Avatar asked May 18 '12 17:05

Backo


People also ask

How do you store percentage?

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).

What is the data type for percentage?

Percents are also their own data type—a number with a percent sign attached. A Percent is stored as a number divided by 100, meaning that 100% is represented as 1, 90% as 0.9, and so on.


1 Answers

It depends a little on how you plan to use the value, but typically a decimal would be a good choice for storing percentages. And note that you could store it as the percentage value (10.01) or as the fractional (.1001). So that would affect the actual size and precision of the column.

The choice between storing as a percent or fraction depends on the usage needs, but I suspect that in most situations it would be simpler to store it as a fraction (e.g., .10 to represent 10%) because it can be used directly in most calculations more easily (don't need to remember to divide by 100).

And as @ismaelga points out in the comments, a decimal is a good choice for accuracy (particularly nice when dealing with monetary calculations).

like image 174
Mark Wilkins Avatar answered Sep 20 '22 09:09

Mark Wilkins