简体   繁体   English

如何存储百分比值?

[英]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.我正在使用 Rails 3.2.2,我想在我的数据库表列中存储处理百分比值。 What do you advice about (for example, what type - :integer , :float , :decimal , ... - of the column should I set)?你有什么建议(例如,我应该设置什么类型 - :integer , :float , :decimal , ... - 列的类型)? Is there some alert that I must/should know about storing percentage values?是否有一些关于存储百分比值我必须/应该知道的警报?

The precision should be 2 ( 1.99% , 50.01% , ...).精度应为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.这在一定程度上取决于您计划如何使用该值,但通常decimal是存储百分比的好选择。 And note that you could store it as the percentage value (10.01) or as the fractional (.1001).请注意,您可以将其存储为百分比值 (10.01) 或小数 (.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).存储为百分比还是分数的选择取决于使用需求,但我怀疑在大多数情况下,将其存储为分数会更简单(例如,0.10 代表 10%),因为它可以直接用于大多数情况计算更容易(不需要记住除以 100)。

And as @ismaelga points out in the comments, a decimal is a good choice for accuracy (particularly nice when dealing with monetary calculations).正如@ismaelga 在评论中指出的那样,小数是准确性的不错选择(在处理货币计算时特别好)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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