如何在 ruby 中保留我的浮点数
所以我正在尝试一些代码将数字转换为字符串。但是,我注意到在某些情况下它不会保留最后两位小数。例如,我输入 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
感谢您的帮助!发布一些代码,以便我可以尝试!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
首先:永远不要使用浮动货币 - 使用浮点或小数来计算会计应用程序美元金额?
但如果非常非常非常想要它:
First of all: never use float for money — Use Float or Decimal for Accounting Application Dollar Amount?
But if want it VERYVERYVERY much:
内容:每个计算机科学家都应该了解浮点运算
阅读以下 ,纳基隆说的。
Read this: What Every Computer Scientist Should Know About Floating-Point Arithmetic
Also, what Nakilon said.
这不是 ruby 的问题,也不是您的代码的问题(尽管您需要摆脱 .en.numwords);这是二进制浮点表示的一个问题。
您应该使用 Fixnum 或 Bignum 来表示货币。
例如。
This is not a problem with ruby, nor your code (although you need to get rid of .en.numwords); it is a problem with the binary floating point representation.
You should use a Fixnum or Bignum to represent the currency.
eg.