MySQL 如何存储百分比值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10656948/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to store a percentage value?
提问by Backo
I am using Rails 3.2.2 and I would like to storeand handlea 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?
我正在使用 Rails 3.2.2,我想在我的数据库表列中存储和处理百分比值。你有什么建议(例如,我应该设置列的什么类型 - :integer
, :float
, :decimal
, ... - )?是否有一些关于存储百分比值我必须/应该知道的警报?
The precision should be 2(1.99%
, 50.01%
, ...).
精度应为2( 1.99%
, 50.01%
, ...)。
Note: I read this post.
注意:我阅读了这篇文章。
回答by Mark Wilkins
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.
这在一定程度上取决于您计划如何使用该值,但通常 adecimal
是存储百分比的不错选择。请注意,您可以将其存储为百分比值 (10.01) 或小数 (.1001)。所以这会影响列的实际大小和精度。
The choice between storing as a percent or fraction depends on the usage needs, but I suspectthat 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).
选择存储为百分比还是分数取决于使用需求,但我怀疑在大多数情况下将其存储为分数会更简单(例如,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 在评论中指出的那样,小数是准确性的不错选择(在处理货币计算时特别好)。