Senthoor
Senthoor

Reputation: 273

Rounding to nearest 100

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

Upvotes: 27

Views: 31386

Answers (7)

Jghorton14
Jghorton14

Reputation: 754

As per Pawan Pillai's comment above, rounding to nearest 100th in Javascript:
100 * Math.floor((foo + 50) / 100);

Upvotes: 2

ktusznio
ktusznio

Reputation: 3595

Ruby's round method can consume negative precisions:

n.round(-2)

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

Upvotes: 68

Timothy Petrakis
Timothy Petrakis

Reputation: 159

I know it's late in the game, but here's something I generally set up when I'm dealing with having to round things up to the nearest nTh:

Number.prototype.roundTo = function(nTo) {
    nTo = nTo || 10;
    return Math.round(this * (1 / nTo) ) * nTo;
}
console.log("roundto ", (925.50).roundTo(100));

Number.prototype.ceilTo = function(nTo) {
    nTo = nTo || 10;
    return Math.ceil(this * (1 / nTo) ) * nTo;
}
console.log("ceilTo ", (925.50).ceilTo(100));

Number.prototype.floorTo = function(nTo) {
    nTo = nTo || 10;
    return Math.floor(this * (1 / nTo) ) * nTo;
}
console.log("floorTo ", (925.50).floorTo(100));

I find myself using Number.ceilTo(..) because I'm working with Canvas and trying to get out to determine how far out to scale.

Upvotes: 5

Nikhil
Nikhil

Reputation: 5771

100 * round(n/100.0)

Upvotes: 8

derobert
derobert

Reputation: 51157

This will do it, given you're using integer math:

n = (n + 50) / 100 * 100

Of course, you didn't specify the behavior of e.g., 1350 and 1450, so I've elected to round up. If you need round-to-even, that'll not work.

Upvotes: 2

David Z
David Z

Reputation: 131600

For input n:

(n + 50) / 100 * 100

using integer division.

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

Upvotes: 40

Brian
Brian

Reputation: 118865

Is this homework?

Generally, mod 100, then if >50 add else subtract.

Upvotes: 0

Related Questions