我正在开发一个非常基本的购物车系统。

我有一个表items,它的列价格类型为整型。

我在视图中显示包含欧元和美分的价格时遇到了麻烦。在Rails框架中处理货币时,我是否遗漏了一些明显的东西?


当前回答

如果你正在使用Postgres(因为我们现在已经是2017年了),你可能想尝试一下他们的:money列。

add_column :products, :price, :money, default: 0

其他回答

我的底层api都使用美分来表示钱,我不想改变这一点。我也没有大量的资金。我把这个放到helper方法中

sprintf("%03d", amount).insert(-3, ".")

它将整数转换为至少有三位数字的字符串(必要时添加前导零),然后在最后两位数字之前插入一个小数点,从不使用Float。从这里,您可以添加任何适合您的用例的货币符号。

这绝对是快速和肮脏的,但有时这是好的!

我是这样用的:

number_to_currency(amount, unit: '€', precision: 2, format: "%u %n")

当然,货币的符号、精度、格式等都取决于每种货币。

处理货币的常见做法是使用十进制类型。 下面是“使用Rails进行敏捷Web开发”中的一个简单示例。

add_column :products, :price, :decimal, :precision => 8, :scale => 2 

这将允许您处理从-999,999.99到999,999.99的价格 你可能还想在你的项目中包括一个验证,比如

def validate 
  errors.add(:price, "should be at least 0.01") if price.nil? || price < 0.01 
end 

检查你的价值观。

你可以将一些选项传递给number_to_currency(一个标准的Rails 4视图帮助器):

number_to_currency(12.0, :precision => 2)
# => "$12.00"

由Dylan Markow发布

您可能希望在数据库中使用DECIMAL类型。在迁移过程中,执行如下操作:

# precision is the total number of digits
# scale is the number of digits to the right of the decimal point
add_column :items, :price, :decimal, :precision => 8, :scale => 2

在Rails中,:decimal类型返回为BigDecimal,这对于价格计算非常有用。

如果您坚持使用整数,那么您将不得不在所有地方手动转换为bigdecimal,这可能会成为一个麻烦。

正如mcl所指出的,要打印价格,请使用:

number_to_currency(price, :unit => "€")
#=> €1,234.01