round a number to the nearest integer in ruby

You can use the round method to round a float or decimal number to its nearest integer. Here is an example:

main.rb
num = 3.6
rounded_num = num.round
puts rounded_num # Output: 4

num = 3.3
rounded_num = num.round
puts rounded_num # Output: 3
127 chars
8 lines

The round method uses the standard rounding rules, so a number that is exactly halfway between two integers will be rounded up to the nearest even integer. For example:

main.rb
num = 4.5
rounded_num = num.round
puts rounded_num # Output: 4

num = 5.5
rounded_num = num.round
puts rounded_num # Output: 6
127 chars
8 lines

If you want to always round up or down, you can use the ceil or floor methods, respectively:

main.rb
num = 3.2
rounded_num = num.ceil
puts rounded_num # Output: 4

num = 3.9
rounded_num = num.floor
puts rounded_num # Output: 3
126 chars
8 lines

gistlibby LogSnag