Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby 2.0 - Rounding an integer to the nearest multiple of 10

Tags:

How do i round an integer to the nearest multiple of ten?

I have tried integer.round(0.1) but it gives the nearest decimal number.

Example: 3 should return 0, 55 should return 60.

Is there a method that will round to the nearest multiple of 10?

like image 614
ooransoy Avatar asked Dec 14 '13 14:12

ooransoy


2 Answers

Integer#round has the functionality.

You pass a negative number to round to represent which 10's digit you'd want to round to. For example:

Round to the nearest 10:

55.round(-1) # => 60 

To round to the nearest 100:

550.round(-2) # => 600 
like image 188
Arup Rakshit Avatar answered Nov 10 '22 02:11

Arup Rakshit


You can just divide by 10, round, then multiply by 10:

nearest = (x/ 10).round * 10 
like image 40
Hunter McMillen Avatar answered Nov 10 '22 01:11

Hunter McMillen