2

所以我正在尝试一些代码来将数字转换为字符串。但是,我注意到在某些情况下,它不会保留最后两位小数。例如,我输入 1.01 和 1.04 进行加法,然后返回 2.04。如果我只输入 1.05 它会保留数字并准确地返回它。我知道发生了什么事情正在四舍五入。我不知道如何防止它被四舍五入。我是否应该只考虑将 (1.01+1.04) 发送给 self 作为一个输入?

警告!我还没有尝试过,所以不知道它是否支持:

 user_input = (1.04+1.01) #entry from user
 user_input = gets.to_f
 user_input.to_test_string

到目前为止我所拥有的:

    class Float
     def to_test_string

      cents = self % 1
      dollars = self - cents
      cents = cents * 100

      text = "#{dollars.to_i.en.numwords} dollars and #{cents.to_i.en.numwords} cents"

      puts text
      text
     end
    end
  puts "Enter two great floating point numbers for adding"
  puts "First number"
  c = gets.to_f
  puts "Second number"
  d = gets.to_f
  e = c+d
  puts e.to_test_string
  puts "Enter a great floating number! Example 10.34"
  a = gets.to_f 
  puts a.to_test_string

谢谢您的帮助!贴一些代码,我可以试试!

4

3 回答 3

2

首先:永远不要将浮点数用于金钱——使用浮点数或小数进行会计应用美元金额?

irb> x = 1.01 + 1.04
=> 2.05
irb> y = x % 1
=> 0.04999999999999982
irb> (y * 100).to_i
=> 4

但是如果非常想要它:

irb> (y * 100).round.to_i
=> 5
于 2010-11-07T22:03:48.497 回答
2
$ python
Python 2.6.2 (release26-maint, Apr 19 2009, 01:56:41)
[GCC 4.3.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> 1.04+1.01
2.0499999999999998

阅读本文:每位计算机科学家应了解的浮点运算知识

还有,Nakilon 说的。

于 2010-11-07T22:12:55.473 回答
1

这不是 ruby​​ 的问题,也不是您的代码(尽管您需要摆脱 .en.numwords);这是二进制浮点表示的问题。

您应该使用 Fixnum 或 Bignum 来表示货币。

例如。

class Currency
    def initialize str
        unless str =~ /([0-9]+)\.([0-9]{2})/
            raise 'invalid currency string'
        end
        @cents = $1.to_i * 100 + $2.to_i
    end
end
于 2010-11-07T22:16:26.433 回答