在 Ruby 中使用 .round 对值进行四舍五入时出错
以下代码段在脚本/控制台中完美运行,但当我在 ruby 脚本中编译相同代码时返回以下错误:
:in `round': wrong number of arguments (1 for 0) (ArgumentError)
tf={"ph"=>{0=>1.33333333333333, 1=>1.5}, "fee"=>{0=>1.66666666666667}, "test"=>{0=>1.16666666666667, 1=>1.25}, "what"=>{0=>2.0, 1=>2.0}, "for"=>{0=>1.5}, "is"=>{0=>1.83333333333333, 1=>1.75}}
tf.each{|k,v| v.each{|k1,v1| tf[k][k1]=(v1.round(5))}}
有什么想法吗?干杯!
The following piece of code works perfectly in script/console but returns the following error when i compile the same in a ruby script.:
:in `round': wrong number of arguments (1 for 0) (ArgumentError)
tf={"ph"=>{0=>1.33333333333333, 1=>1.5}, "fee"=>{0=>1.66666666666667}, "test"=>{0=>1.16666666666667, 1=>1.25}, "what"=>{0=>2.0, 1=>2.0}, "for"=>{0=>1.5}, "is"=>{0=>1.83333333333333, 1=>1.75}}
tf.each{|k,v| v.each{|k1,v1| tf[k][k1]=(v1.round(5))}}
Any Ideas ? Cheers !
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Float#round
似乎在 Ruby 1.8< 中工作方式不同< /a> 和 Ruby 1.9:在 1.8 中它抱怨给定的参数,在 1.9 中返回正确舍入到给定小数位数的浮点数。但是,正如文章中链接的那样其他答案明智地说:
Float#round
seems to work differently in Ruby 1.8 and Ruby 1.9: in 1.8 it complains about the given argument, in 1.9 returns back float properly rounded to the given number of decimals.But, as the article linked in the other answer wisely says:
从表面上看,您不应该将参数传递给 round 方法。你已经通过了 5 分。
如果您尝试将其四舍五入到小数点后 5 位,则没有内置方法(据我所知)。此页面解释了如何执行此操作: http ://solutions.hans-eric.com/rounding-off-floating-point-numbers-in-ruby
From what it looks like, you are not supposed to pass an argument to the round method. You have passed 5 to it.
If you are trying to round it to 5 decimal places, there is no builtin method for that (that I'm aware of). This is a page that explains how to do so: http://solutions.hans-eric.com/rounding-off-floating-point-numbers-in-ruby