Ruby Integer truncate() function with example

The truncate() function in Ruby returns an int truncated value to a precision of ndigits decimal digits. When the precision is negative, the returned value is an integer with at least ndigits.abs trailing zeros. It returns itself when ndigits is zero or positive. The default value of ndigits is considered to be zero.

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.

Example #1:

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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

chevron_right


Output:

100
100
-10
120

Example #2:

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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

chevron_right


Output:

190
10
10
1123


My Personal Notes arrow_drop_up

The function of education is to teach one to think intensively and to think critically

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.