当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Ruby Numeric round()用法及代码示例


round()是Ruby中的一个内置方法,它返回一个四舍五入到一个最接近给定数字的数字,并精确到小数点后的给定数字位数。如果未提供数字位数,则默认值为零。

用法: num.round(ndigits)

参数:该函数需要一个数字和一个n位数字,以指定要四舍五入的位数。如果未给出ndigits,则默认值为零。


返回值:返回四舍五入的值。

例子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


相关用法


注:本文由纯净天空筛选整理自gopaldave大神的英文原创作品 Ruby | Numeric round() function。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。