Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rounding to nearest 100

Tags:

algorithm

First number needs to be rounded to nearest second number. There are many ways of doing this, but whats the best and shortest algorithm? Anyone up for a challenge :-)

1244->1200
1254->1300
123->100
178->200
1576->1600
1449->1400
123456->123500
654321->654300
23->00
83->100

like image 218
Senthoor Avatar asked Feb 25 '09 06:02

Senthoor


People also ask

Whats 350 rounded to the nearest 100?

350 rounded to the nearest 100 is rounded up to 400.

Whats 127 rounded to the nearest 100?

The number 127 is less than the halfway number . So, 127 is nearer to 100 than to 200 . 100 is the nearest hundred to 127 .

What does round to 100 mean?

Rounding to the nearest 100 means to write the multiple of 100 that is nearest to the number. Either the hundreds digit will remain the same or it will increase by one. 379 is in between 300 and 400, so the options are to round down to 300 or round up to 400.


2 Answers

Ruby's round method can consume negative precisions:

n.round(-2)

In this case -2 gets you rounding to the nearest hundred.

like image 80
ktusznio Avatar answered Sep 21 '22 15:09

ktusznio


For input n:

(n + 50) / 100 * 100 

using integer division.

Note that many languages/libraries already have functions to do this.

like image 29
David Z Avatar answered Sep 22 '22 15:09

David Z