Ruby Integer truncate()函数与示例
Ruby 中的truncate()函数返回一个 int 截断值,精度为ndigits十进制数字。当精度为负时,返回值是一个整数,至少ndigits.abs尾随零。当ndigits为零或正数时,它会返回自身。 ndigits 的默认值被认为是零。
Syntax: number.truncate(ndigits)
Parameter: The function takes the integer which is to be truncated and a non-mandatory ndigits, upto which it has to be truncated.
Return Value: The function returns the truncated value to a precision of ndigits.
示例 #1:
# Ruby program for truncate function
# Initializing the number
num1 = 120
ndigits1 = -2
num2 = 120
ndigits2 = -2
num3 = -19
ndigits3 = -1
num4 = 120
# Prints the truncated value
puts num1.truncate(ndigits1)
puts num2.truncate(ndigits2)
puts num3.truncate(ndigits3)
puts num4.truncate
输出:
100
100
-10
120
示例 #2:
# Ruby program for truncate function
# Initializing the number
num1 = 190
ndigits1 = -1
num2 = 10
ndigits2 = 2
num3 = 18
ndigits3 = -1
num4 = 1123
# Prints the truncated value
puts num1.truncate(ndigits1)
puts num2.truncate(ndigits2)
puts num3.truncate(ndigits3)
puts num4.truncate
输出:
190
10
10
1123