50

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.

1
  • 2
    So, after reading that post, what is still unclear to you? May 18, 2012 at 17:14

1 Answer 1

61

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

7
  • 2
    Agreed, decimal is good since he has a particular precision in mind.
    – coder_tim
    May 18, 2012 at 17:22
  • 1
    I would add in this question that decimal is good so there is accuracy and no need for convercions from float to decimal. May 18, 2012 at 17:22
  • 1
    @ismaelga: Very good point. I added that information. Thanks. May 18, 2012 at 17:31
  • 2
    OK, I found that: api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/…
    – Backo
    May 18, 2012 at 17:39
  • 2
    @nicco: Note that decimal here refers to a precise numeric representation. It is not the same as float, which is a type that typically refers to the IEEE 754 standard. Use google to find the differences. And don't use float to represent monetary values. Apr 7, 2016 at 13:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.