处理货币/金钱的最佳方法是什么? [英] What is the best method of handling currency/money?

查看:29
本文介绍了处理货币/金钱的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm working on a very basic shopping cart system.

我有一个表 items,其中有一列 price 类型为 integer.

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 BigDecimals 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屋!

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