Ruby | Numeric truncate() function
Last Updated :
19 Mar, 2024
The truncate() is an inbuilt method in Ruby returns a number rounded toward zero with a precision of the given number of digits after the decimal point. In case the number of digits is not given, the default value is taken to be zero.
Syntax: num.truncate(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.
Example 1:
num1 = - 16 . 7834
num2 = - 16 . 78324
num3 = 16 . 873
puts num1.truncate( 1 )
puts num2.truncate()
puts num3.truncate()
|
Output:
-16.7
-16
16
Example 2:
num1 = 12 . 32
num2 = - 1321 . 998321
num3 = - 12 . 2321
puts num1.truncate( 1 )
puts num2.truncate( 2 )
puts num3.truncate( 3 )
|
Output:
12.3
-1321.99
-12.232
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...