简体   繁体   中英

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 .

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 (eg, .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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM