2010-11-07 40 views
2

所以我想一些代码转换成字符串的数字。但是,我注意到在某些情况下它不保留最后两位小数。例如我输入1.01和1.04添加,然后回到2.04。如果我输入的只是1.05,它会保留这个数字并将其准确返回。我知道事情正在变得圆满。我不知道如何防止它被四舍五入。我应该只考虑发送(1.01 + 1.04)给自己作为一个输入吗?如何保存我的浮点数在红宝石

警告!我还没有试过这种又那么不知道它支持:

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 

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

+0

是'en'和'numwords' Ruby方法,还是来​​自Rails的ActiveSupport? – 2010-11-07 22:11:40

+0

@Andrew Grimm,我诚恳地认为,它绝对不能成为Ruby的核心或stdlib。 – Nakilon 2010-11-07 22:20:54

+0

@Nakilon:我同意。我只是问,因为这个问题最初只是标记为'ruby'而不是'ruby-on-rails'。 – 2010-11-07 22:38:12

回答

1

这不是一个红宝石问题,也不是你的代码(尽管你需要摆脱.en.numwords);它是带有二进制浮点表示的a problem

您应该使用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