JRuby 1.6.x.如何将浮点数舍入到jruby中的小数位数。
number = 1.1164
number.round(2)
The above shows the following error
wrong number of arguments (1 for 0)
如何将此舍入为2位小数?
答案 0 :(得分:263)
(5.65235534).round(2)
#=> 5.65
答案 1 :(得分:173)
sprintf('%.2f', number)
是一种神秘数字格式的神秘方式。结果总是一个字符串,但是因为你正在四舍五入,所以我认为你是为了演示目的而做的。 sprintf
几乎可以按照您喜欢的方式格式化任何数字,还有更多。
完整的sprintf文档:http://www.ruby-doc.org/core-2.0.0/Kernel.html#method-i-sprintf
答案 2 :(得分:85)
Float#round可以在Ruby 1.9中使用参数,而不是在Ruby 1.8中。 JRuby默认为1.8,但它能够running in 1.9 mode。
答案 3 :(得分:1)
获得反馈后,原来的解决方案似乎无法正常工作。这就是为什么更新答案作为建议之一。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<CheckBox
android:layout_width="wrap_content"
android:layout_height="19dp"
android:text="Add"
android:id="@+id/checkBox"
android:layout_gravity="right"
android:translationY="25dp"
android:translationX="0dp"
android:layout_marginLeft="280dp"
android:focusable="false"/>
<TextView
android:id="@+id/txt"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="5dp"
/>
</LinearLayout>
如果您想要包含2位小数的舍入数,则其他答案可能有效。但是,如果你想让前两位小数的浮点数没有舍入,那些答案就不会有帮助。
因此,为了获得前两位小数的浮点数,我使用了这种技术。 在某些情况下不起作用
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
。希望它会帮助某人
答案 4 :(得分:-4)
试试这个:
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
答案 5 :(得分:-14)
截断小数我使用了以下代码:
<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