Ruby Float round()方法及示例
round()是一个float类的方法,它返回一个四舍五入的浮点数,精度为n位小数。
语法:float.round()
参数:浮动值作为参数
返回四舍五入到最近精度的浮点数
如果精度为-ve:整数,至少有ndigits.abs尾部的零
如果ndigits为+ve:一个浮点数,否则为整数
例子 #1 :
# Ruby code for round() method
# declaring float value
a = 0.767
# declaring float value
b = 2999.011
# rounding the float value
puts "rounding a : #{a.round}\n\n"
# rounding the float value
puts "rounding b : #{b.round}\n\n"
输出:
rounding a : 1
rounding b : 2999
例子 #2 :
# Ruby code for round() method
# declaring float value
a = 0.767
# declaring float value
b = 2999.011
# declaring float value
c = 2.0000
# rounding the float value
puts "round a : #{a.round(2)}\n\n"
# rounding the float value
puts "round b : #{b.round(-2)}\n\n"
# rounding the float value
puts "round c : #{c.round(0)}\n\n"
输出:
round a : 0.77
round b : 3000
round c : 2