How to store a percentage value?
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).
Related videos on Youtube
Backo
Updated on July 09, 2022Comments
-
Backo almost 2 years
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.
-
Sergio Tulentsev almost 12 yearsSo, after reading that post, what is still unclear to you?
-
-
coder_tim almost 12 yearsAgreed, decimal is good since he has a particular precision in mind.
-
Ismael almost 12 yearsI would add in this question that decimal is good so there is accuracy and no need for convercions from float to decimal.
-
Mark Wilkins almost 12 years@ismaelga: Very good point. I added that information. Thanks.
-
Backo almost 12 yearsSo my statement should be
add_column :worker, :percentage, :decimal, :precision => 2
? Where I can find more information about stating decimal values? -
Backo almost 12 yearsOK, I found that: api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/…
-
Nico about 8 yearsI've read your question but with languages variables we have some trouble in precision when dealing with decimals. 0.2 can't be precisely represented for example, some people advise to avoid decimals in monetary calculation. groovyconsole.appspot.com/script/5078068011991040 what's your advice about this ?
-
Mark Wilkins about 8 years@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.