处理货币/货币的最佳方法是什么? [英] What is the best method of handling currency/money?
问题描述
我正在开发一个非常基本的购物车系统。
I'm working on a very basic shopping cart system.
我有一个表项
,该表的列 price
类型为整数
的>。
I have a table items
that has a column price
of type integer
.
我无法在包含欧元和美分的价格视图中显示价格值。就在Rails框架中处理货币而言,我是否缺少明显的东西?
I'm having trouble displaying the price value in my views for prices that include both Euros and cents. Am I missing something obvious as far as handling currency in the Rails framework is concerned?
推荐答案
您可能想使用在数据库中输入 DECIMAL
。在您的迁移中,执行以下操作:
You'll probably want to use a DECIMAL
type in your database. In your migration, do something like this:
# 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
,这对价格计算非常有用。
In Rails, the :decimal
type is returned as BigDecimal
, which is great for price calculation.
如果您坚持使用整数,则可以手动在 BigDecimal
之间进行转换,这可能会很痛苦。
If you insist on using integers, you will have to manually convert to and from BigDecimal
s everywhere, which will probably just become a pain.
mcl,要打印价格,请使用:
As pointed out by mcl, to print the price, use:
number_to_currency(price, :unit => "€")
#=> €1,234.01
这篇关于处理货币/货币的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!