在 Ruby on Rails 3 中使用小数 [英] Working with decimals in Ruby on Rails 3

查看:39
本文介绍了在 Ruby on Rails 3 中使用小数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试计算产品的平均净价.我的产品模型中有:total_sold 和:total_net_revenue.在方法中进行直接除法似乎总是导致 0.我诉诸于使用 BigDecimal,因为我认为这是问题......但是在我对下面代码的最新迭代中,当答案出来时,我仍然得到零一个小数.

I'm trying to calculate the average net price of a product. I have, in my Product model :total_sold and :total_net_revenue. Doing straight division in the method seems to always result in 0. I resorted to using BigDecimal as I figured that was the problem ... but with my latest iteration of the code below, I'm still getting zero when the answer comes out to a decimal.

def avg_price
  BigDecimal(total_sold.to_s) / (BigDecimal(total_net_revenue.to_s) / 100)
end  

净收入以美分为单位,这就是我除以 100 的原因.有人可以指出我做错了什么或应该做什么吗?

Net revenue is in cents, which is why I divide by 100. Can someone point out what I'm doing wrong or should do?

推荐答案

total_net_revenue / total_sold

total_net_revenue / total_sold / 100.0

total_net_revenue.to_f / total_sold / 100

如果需要,这三种方法可以提高精度.请记住,平均价格"是平均价格/销售额.这是每件商品的钱,因此您需要按特定顺序进行划分.

These three methods give an increasing amount of precision, if you want it. Remember that "average price" is "average price / sale. That's money-per-item so you will want to do the division in that specific order.

这篇关于在 Ruby on Rails 3 中使用小数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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