红宝石 |数字 round()函数
round()是 Ruby 中的一个内置方法,它返回一个四舍五入到最接近给定数字的数字,精度为小数点后给定的位数。如果未给出位数,则默认值为零。
Syntax: num.round(ndigits)
Parameters: The function needs a number and ndigits which specifies the number of digits to be rounded off. If ndigits is not given then, default value is taken to be zero.
Return Value: It returns the rounded value.
示例 1 :
# Ruby program for round()
# method in Numeric
# Initialize a number
num1 = -16.7834
num2 = -16.78324
num3 = 16.873
# Prints round
puts num1.round(1)
puts num2.round()
puts num3.round()
输出:
-16.8
-17
17
示例 2 :
# Ruby program for round()
# method in Numeric
# Initialize a number
num1 = 12.32
num2 = -1321.998321
num3 = -12.2321
# Prints round
puts num1.round(1)
puts num2.round(2)
puts num3.round(3)
输出:
12.3
-1322.0
-12.232