Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I round an integer up to <nearest large number> in Ruby?

Say I have any of the following numbers:

230957 or 83487 or 4785

What is a way in Ruby I could return them as 300000 or 90000 or 5000, respectively?

like image 735
John Avatar asked Aug 03 '10 21:08

John


People also ask

How do you round to the nearest whole number in Ruby?

Ruby | Numeric round() function The round() is an inbuilt method in Ruby returns a number rounded to a number nearest to the given number 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.

How do you round up in Ruby?

The round() method can be used to round a number to a specified number of decimal places in Ruby. We can use it without a parameter ( round() ) or with a parameter ( round(n) ). n here means the number of decimal places to round it to.

How do you round up to the nearest integer?

To round a number to the nearest whole number, you have to look at the first digit after the decimal point. If this digit is less than 5 (1, 2, 3, 4) we don't have to do anything, but if the digit is 5 or greater (5, 6, 7, 8, 9) we must round up.

Does Ruby round up or down?

Ruby Language Numbers Rounding Numbers The round method will round a number up if the first digit after its decimal place is 5 or higher and round down if that digit is 4 or lower.


1 Answers

Math.round accepts negative numbers. If you are only looking for the nearest 10, you can do (my_num).round(-1).

The only drawback being that there's no way to incorporate ceil here, so it doesn't always round up -- 4.round(-1) will return 0.

like image 87
c.apolzon Avatar answered Sep 29 '22 21:09

c.apolzon