如何用Ruby中的浮点数除美元和美分

az31mfrm  于 2023-04-29  发布在  Ruby
关注(0)|答案(1)|浏览(84)

我是Ruby新手,我有一个任务来实现一个有两个变量的类-美元和美分。它必须有一个方法来将这个量除以一个浮点数。

class Money
    def initialize(d,c)
      @dollars = d
      @cents = c
   end
    def divide(num)
        @dollars=(@dollars.to_f / num)
        puts @dollars.to_s
        @cents=(@cents.to_f / num).round+(@cents.to_f-@cents.to_i.to_f).round
        puts @cents.to_s
        @dollars=@cents.to_i
        puts "After dividing by #{num}: #{@dollars},#{@cents}"
    end
end
m=Money.new(100,69)
m.divide(2.1)

然而,这种方法不能正确地计算它。结果应该是47,95,但它是47,34。正如您所看到的,它正确地计算了美元,但无法计算美分。我试过模运算,但也失败了。
将感谢任何帮助!

cld4siwp

cld4siwp1#

如果你想自己做这件事而不是使用gem库,你应该使用整数而不是浮点数,因为后者固有的不精确性会导致累积错误。您还应该决定小数点是应该四舍五入还是截断。提示:大多数银行和商家将四舍五入的费用和截断支出或作出改变。
尝试以下操作:

class Money
  def initialize(d, c)
    @cents = 100 * d.to_i + c.to_i
  end

  def dollars
    @cents / 100            # integer division truncates
  end

  def cents
    @cents % 100
  end

  def divide(divisor, round_method: :floor)
    if round_method == :floor
      Money.new(0, @cents / divisor)
    else
      Money.new(0, (@cents.to_f / divisor).send(round_method))
    end
  end

  def to_s
    d, c = @cents.divmod(100)
    "#{d}.#{'%02d' % c}"    # Format cents to two digits w/ leading zeros
  end
end

m = Money.new(100, 69)
puts m.divide(2.1)                          # 47.94
puts m.divide(2.1, round_method: :round)    # 47.95
puts m.divide(1000)                         # 0.10

正如您所看到的,如果使用舍入,它会产生您想要的结果,但是如果使用截断(floor),则会产生一个微小的差异。
请注意,如果使用舍入,则必须单步执行浮点计算,但应立即转换回整数。

相关问题