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
350 rounded to the nearest 100 is rounded up to 400.
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 .
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.
Ruby's round method can consume negative precisions:
n.round(-2)
In this case -2 gets you rounding to the nearest hundred.
For input n
:
(n + 50) / 100 * 100
using integer division.
Note that many languages/libraries already have functions to do this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With