所以我想一些代碼轉換成字符串的數字。但是,我注意到在某些情況下它不保留最後兩位小數。例如我輸入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
感謝您的幫助!張貼一些代碼,以便我可以嘗試!
是'en'和'numwords' Ruby方法,還是來自Rails的ActiveSupport? – 2010-11-07 22:11:40
@Andrew Grimm,我誠懇地認爲,它絕對不能成爲Ruby的核心或stdlib。 – Nakilon 2010-11-07 22:20:54
@Nakilon:我同意。我只是問,因爲這個問題最初只是標記爲'ruby'而不是'ruby-on-rails'。 – 2010-11-07 22:38:12