在Rails + MySQL中存储百分比 [英] Storing a percentage in Rails + MySQL

查看:137
本文介绍了在Rails + MySQL中存储百分比的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在Rails应用程序中使用一个百分比.在任何视图中(包括用户输入的时间),格式都必须为百分号格式100.000.在计算中使用它时,它必须以百分数格式1.00000表示.

I need to use a percentage in my Rails app. In any view, including when it is entered by the user, the format will need to be the hundreds format, 100.000. When it's used in calculations, it needs to be represented in the hundredths format, 1.00000.

我的迁移(我将列添加到现有表中)具有以下行:

My migration (I'm adding the column to an existing table) has the following line:

add_column :worker, :cash_split, :decimal, :precision => 6, :scale => 5

因此,截至目前,我以百分之一百(1.00000)格式存储它.我选择以这种格式存储它的基础是,我认为当我需要进行乘法运算时,这将意味着更清晰的业务逻辑(即没有worker.cash_split / 100.0.to_d代码徘徊).

So, as of right now, I'm storing it in the hundredths (1.00000) format. My basis for choosing to store it in this format is that i figure it will mean cleaner business logic (i.e. no worker.cash_split / 100.0.to_d code hanging around) when i need to do multiplication.

我唯一的其他想法可能是滥用composed_of方法.我可以将数百种(100.000)格式的数据存储为cash_split,然后创建一个属性访问器cash_split_percentage,以其1.0000格式返回cash_split.

My only other thought was maybe abusing the composed_of method. I could store the data in the hundreds (100.000) format as cash_split and then make an attribute accessor cash_split_percentage that returns cash_split in its 1.0000 format counterpart.

推荐答案

您的第一个想法是正确的...不要想得太多.

Your first thought is the right one...don't overthink it.

您绝对应该以百分之百格式将百分比数字存储在数据库中.并在所有Ruby计算中使用该格式.

You should definitely store percentage numbers in the database in hundredths format. And use that format in all of your Ruby calculations.

百分比数字是 display 惯例.例如,数字 0.45显示为45%.因此,请使用View帮助程序将百分比数字从其内部格式(十进制数字)转换为所选的显示格式-包含%符号的字符串.

Percentage figures are a display convention. Eg the number 0.45 is displayed as 45%. As such, use a View helper to convert your percentage figures from their internal format (decimal numbers) to your chosen display format--a string which includes the % sign.

这篇关于在Rails + MySQL中存储百分比的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆