在JRuby(1.6.x)中,如何将浮点数保留两位小数并四舍五入?
number = 1.1164
number.round(2)
# The above shows the following error
# wrong number of arguments (1 for 0)
(5.65235534).round(2)
#=> 5.65
sprintf('%.2f', number)
是一种晦涩但非常强大的数字格式化方式。其结果总是一个字符串,但由于你正在四舍五入,我假设你是为了呈现目的而这样做的。sprintf
可以以几乎任何你喜欢的方式格式化任何数字,还有更多。
sprintf
(或者format
)而不是 %
版本。这个决定的一些理由在这里被讨论了,主要考虑到代码的可读性。并不是每个人都需要遵循这个风格指南,只是提供一些原因 :) - Lucy Bain5
四舍五入到小数点后一位的偶数,有什么解决办法吗? - Mirror318在Ruby 1.9中,Float#round可以带有一个参数,而在Ruby 1.8中则不行。JRuby默认为1.8版本,但它能够运行在1.9模式下。
收到反馈后,原来的解决方案似乎不起作用。因此,我根据建议更新了答案。
def float_of_2_decimal(float_n)
float_n.to_d.round(2, :truncate).to_f
end
如果您想要保留两位小数的四舍五入数字,其他答案可能有效。但是,如果您想要保留前两位小数点不进行四舍五入,那么这些答案将无法帮助您。
因此,为了获得一个带有前两位小数点的浮点数,我使用了这个技巧。在某些情况下可能不适用
def float_of_2_decimal(float_n)
float_n.round(3).to_s[0..3].to_f
end
使用 5.666666666666666666666666
,它会返回 5.66
而不是四舍五入后的 5.67
。希望对某些人有所帮助。
float_n.to_d.round(2,:truncate).to_f
。 - rorykoehler11111111111111111.222222222222222
,第一个显示 1.11
,第二个显示 1.11111111111111e+16
。 - Anwar'111111111111111111111111.222222'.to_d.round(2, :truncate).to_f
返回 1.1111111111111111e+23
。但如果你移除最后一个 .to_f
,它就可以正常工作。 - lacostenycoder试试这个:
module Util
module MyUtil
def self.redondear_up(suma,cantidad, decimales=0)
unless suma.present?
return nil
end
if suma>0
resultado= (suma.to_f/cantidad)
return resultado.round(decimales)
end
return nil
end
end
end
为了截断小数,我使用了以下代码:
<th><%#= sprintf("%0.01f",prom/total) %><!--1dec,aprox-->
<% if prom == 0 or total == 0 %>
N.E.
<% else %>
<%= Integer((prom/total).to_d*10)*0.1 %><!--1decimal,truncado-->
<% end %>
<%#= prom/total %>
</th>
Integr(a*100)*0.01
。
(5.6).round(2)
返回的结果仅为 5.6。 - Bala Karthik