在JRuby(1.6.x)中,如何将浮点数舍入到小数点后两位?
number = 1.1164
number.round(2)
# The above shows the following error
# wrong number of arguments (1 for 0)
发布于 2012-05-06 00:06:23
Float#round可以接受Ruby1.9中的参数,但不能接受Ruby1.8中的参数。JRuby默认为1.8,但它支持running in 1.9 mode。
发布于 2013-02-28 17:29:47
(5.65235534).round(2)
#=> 5.65
发布于 2012-05-11 04:45:49
sprintf('%.2f', number)
是一种神秘但非常强大的数字格式化方法。结果总是一个字符串,但是由于您是在舍入,所以我假设您这样做是为了表示目的。sprintf
几乎可以按您喜欢的任何方式格式化任何数字,甚至更多。
完整的sprintf文档:http://www.ruby-doc.org/core-2.0.0/Kernel.html#method-i-sprintf
https://stackoverflow.com/questions/10459901
复制相似问题