如何将浮点数舍入到jruby中的两个小数位

Sam*_*Sam 163 ruby jruby rounding

JRuby 1.6.x. 如何将浮点数舍入到jruby中的小数位数.

number = 1.1164
number.round(2)

The above shows the following error
wrong number of arguments (1 for 0)
Run Code Online (Sandbox Code Playgroud)

如何将其舍入到2位小数?

bou*_*uby 275

(5.65235534).round(2)
#=> 5.65
Run Code Online (Sandbox Code Playgroud)

  • `(5.6).round(2)`只返回5.6 (11认同)
  • 似乎是合理的,额外的零占位符仍然存在,它只是不可见 (3认同)

The*_*heo 186

sprintf('%.2f', number)是一种神秘的,但非常强大的数字格式化方式.结果总是一个字符串,但是因为你正在四舍五入,所以我认为你是为了演示目的而做的.sprintf可以按照您喜欢的任何方式格式化任何数字,还有更多.

完整的sprintf文档:http://www.ruby-doc.org/core-2.0.0/Kernel.html#method-i-sprintf

  • `'%.2f'%number`也更常见,至少在我的经验中如此. (74认同)
  • @MichaelKohl [ruby风格指南](https://github.com/bbatsov/ruby-style-guide#sprintf)赞成`%'版本的`sprintf`(或`format`).[这里]讨论了一些推理(http://batsov.com/articles/2013/06/27/the-elements-of-style-in-ruby-number-2-favor-sprintf-format-over- string-number-percent /),主要是关于可读性.并不是说我们都必须遵循风格指南,只是给出了一些理由:) (6认同)
  • 请注意,在第3个小数后,sprintf在6上而不是在5上,例如,sprintf("%.3f",1.2225)将为"1.222",sprintf("%.3f",1.2226)将为"1.223" ",如果这对您很重要,请坚持使用#round (3认同)

ste*_*lag 85

Float#round可以在Ruby 1.9中使用参数,而不是在Ruby 1.8中.JRuby默认为1.8,但它能够以1.9模式运行.


Anw*_*war 6

编辑

得到反馈后,原来的解决方案似乎不起作用。这就是为什么将答案更新为建议之一。

def float_of_2_decimal(float_n) 
  float_n.to_d.round(2, :truncate).to_f
end
Run Code Online (Sandbox Code Playgroud)

如果您想要四舍五入到小数点后两位的数字,其他答案可能会起作用。但是,如果您想要具有前两位小数的浮点数而不进行四舍五入,那么这些答案将无济于事。

因此,为了获得具有前两位小数的浮点数,我使用了这种技术。在某些情况下不起作用

def float_of_2_decimal(float_n)
  float_n.round(3).to_s[0..3].to_f
end
Run Code Online (Sandbox Code Playgroud)

使用5.666666666666666666666666,它将返回5.66而不是舍入5.67。希望它能帮助某人