Ruby Float round() 方法与示例
round()是一个浮点类方法,它返回一个浮点值,它以 n 位十进制数字精度四舍五入到最接近的值。
Syntax: float.round()
Parameter: float value as argument
Return: Float value rounded to nearest precision
If precision is -ve : integer with at least ndigits.abs trailing zeros
If ndigits is +ve : a floating-point number, otherwise integer
示例 #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