如何控制浮点计算中的小数?

时间:2014-01-29 20:07:38

标签: ruby-on-rails ruby ruby-on-rails-4 console irb

我正在尝试运行一些计算以表示特定价格(即20.30)。

我尝试过Float#round方法,但是保存这些值的实例变量最终会在几次计算后开始表示看起来像24.43418的数字。

这只是我创建的用于将用户输入转换为百分比的方法

class Fixnum
 def percentage
  self.to_f / 100
 end
end

@ bankroll_amount和@risk_amount值应该评估为两个小数点

class Client

 def initialize(bankroll, unit)
  @bankroll_amount = bankroll.to_i.round(2)
  @unit_percentage = unit.to_i.percentage
  default_risk_amount.round(2)
  evaluate_default_unit!.round(2)
 end

 def default_risk_amount
  @risk_amount = @unit_percentage * @bankroll_amount
  @risk_amount.round(2)
 end

 # simulates what an updated bankroll looks like after a win based on clients "unit"  amount
 def risk_win
  @bankroll_amount = @bankroll_amount + @risk_amount
  @bankroll_amount.round(2)
  evaluate_default_unit!.round(2)
 end

 # simulates what a clients updated bankroll looks like after a loss based on clients "unit" amount
 def risk_loss
  @bankroll_amount = @bankroll_amount - @risk_amount
  evaluate_default_unit!
 end


 def evaluate_default_unit!
  @risk_amount = @unit_percentage * @bankroll_amount.round(2)
 end

end

我不确定这是否与我正在初始化这些实例变量的事实有关,但@risk_amount返回正确的两位小数值,但是当我返回对象时,里面的实例变量有运行小数

c = Client.new 2000, 1
<Client:0x000001018956a0 @bankroll_amount=2000.0, @unit_percentage=0.01, @risk_amount=20.0>

c.risk_win
=> 20.2

当我足够运行c.risk_win时,它最终返回

c
<Client:0x000001018956a0 @bankroll_amount=2440.3802, @unit_percentage=0.01, @risk_amount=24.4038>

2 个答案:

答案 0 :(得分:2)

这是仅显示两个小数点的一种方法。

price = 20.21340404
"%.2f" % price
# => 20.23

另见RAILS number_to_currency助手ActionView::Helpers::NumberHelper

http://api.rubyonrails.org/classes/ActionView/Helpers/NumberHelper.html#method-i-number_to_currency

答案 1 :(得分:1)

使用number_with_precision将浮点数的显示格式设置为2位小数:

number_with_precision(@bankroll_amount.to_f, precision: 2)

rails控制台中的用法:

[1] pry(main)> include ActionView::Helpers::NumberHelper
=> Object
[2] pry(main)> number_with_precision(2440.3802, precision: 2)
=> "2440.38"