如何保存红宝石中的浮点数 [英] How do I preserve my float number in ruby
问题描述
因此,我正在尝试一些代码以将数字转换为字符串.但是,我注意到在某些情况下它不会保留最后两位小数.例如,我键入1.01和1.04作为加法,然后得到2.04.如果我只输入1.05,它将保留该数字并准确返回.我知道发生了什么事.我不知道如何防止它被四舍五入.我是否应该只考虑将(1.01 + 1.04)发送给self作为一个输入?
So I'm trying some code out to convert numbers into strings. However, I noticed that in certain cases it does not preserve the last two decimal places. For instance I type 1.01 and 1.04 for addition and I get back 2.04. If I type just 1.05 it preserves the number and returns it exactly. I get whats going on things are being rounded. I don't know how to prevent it from being rounded though. Should I just consider sending (1.01+1.04) to self as only one input?
警告!我还没有尝试过,所以不知道它是否受支持:
Warning! I haven't tried this yet so don't know if its supported:
user_input = (1.04+1.01) #entry from user
user_input = gets.to_f
user_input.to_test_string
到目前为止我所拥有的:
What I have so far:
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
感谢您的帮助!张贴一些代码,以便我可以尝试!
Thanks for the help! Post some code up so I can try!
推荐答案
First of all: never use float for money — Use Float or Decimal for Accounting Application Dollar Amount?
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
这篇关于如何保存红宝石中的浮点数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!