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)
The*_*heo 186
sprintf('%.2f', number)是一种神秘的,但非常强大的数字格式化方式.结果总是一个字符串,但是因为你正在四舍五入,所以我认为你是为了演示目的而做的.sprintf可以按照您喜欢的任何方式格式化任何数字,还有更多.
完整的sprintf文档:http://www.ruby-doc.org/core-2.0.0/Kernel.html#method-i-sprintf
得到反馈后,原来的解决方案似乎不起作用。这就是为什么将答案更新为建议之一。
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。希望它能帮助某人
| 归档时间: |
|
| 查看次数: |
211788 次 |
| 最近记录: |