【发布时间】:2020-10-23 18:31:57
【问题描述】:
如何在 JRuby(1.6.x) 中将浮点数四舍五入到小数点后 2 位?
number = 1.1164
number.round(2)
# The above shows the following error
# wrong number of arguments (1 for 0)
【问题讨论】:
如何在 JRuby(1.6.x) 中将浮点数四舍五入到小数点后 2 位?
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
【讨论】:
(5.6).round(2) 仅返回 5.6
sprintf('%.2f', number) 是一种神秘但非常强大的数字格式化方式。结果始终是一个字符串,但是由于您正在四舍五入,我假设您这样做是为了演示目的。 sprintf 几乎可以以任何你喜欢的方式格式化任何数字,还有更多。
完整的 sprintf 文档:http://www.ruby-doc.org/core-2.0.0/Kernel.html#method-i-sprintf
【讨论】:
'%.2f' % number 也更常见,至少在我的经验中是这样。
% 版本的 sprintf(或 format)。 here 讨论了一些原因,主要是关于可读性。并不是说我们都必须遵循样式指南,只是给出一些理由:)
"%.2f" 轮到 5 向下而不是向上,有什么办法可以解决这个问题吗?
Float#round 可以在 Ruby 1.9 中使用参数,而不是在 Ruby 1.8 中。 JRuby 默认为 1.8,但它支持running in 1.9 mode。
【讨论】:
得到反馈后,原来的解决方案似乎不起作用。这就是为什么将答案更新为建议之一。
def float_of_2_decimal(float_n)
float_n.to_d.round(2, :truncate).to_f
end
如果您希望获得小数点后 2 位的四舍五入数字,其他答案可能会起作用。但是,如果您想获得前两位小数的浮点数不四舍五入,那么这些答案将无济于事。
所以,为了获得前两位小数的浮点数,我使用了这种技术。 在某些情况下不起作用
def float_of_2_decimal(float_n)
float_n.round(3).to_s[0..3].to_f
end
使用5.666666666666666666666666,它将返回5.66,而不是四舍五入的5.67。希望它会帮助某人
【讨论】:
def float_of_2_decimal(float_n) num = float_n.to_s.split('.') num[1] = num[1][0..1] num.join(".").to_f end 或者更简单,您可以使用 float_n.to_d.round(2, :truncate).to_f
'111111111111111111111111.222222'.to_d.round(2, :truncate).to_f 返回1.1111111111111111e+23。但是,如果您删除最后一个 .to_f,它会起作用
试试这个:
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>
如果你想截断到 2 位小数,你应该使用Integr(a*100)*0.01
【讨论】: