prem89 - 9 months ago 53

Javascript Question

In javascript what's the simplest way to find the next even 100 ("even 100" = 200, 400, etc.) that's closest to the given number. For ex: 1723 should return 1800, 1402 should return 1600, 21 should return 200, 17659 should return 17800 etc. I have the following that finds the nearest 100 next to the given_num but not the even 100

`(parseInt(((given_num + 99) / 100 )) * 100 )`

I can think of one way of getting the number without zeroes and checking if its odd/even to figure out next even number if its odd.But more curious to see if there's some simple/elegant way.

Answer

Based on bmb's comment, it sounds like you want granularity of 200, not 100. If so:

Divide by 200, round up, multiply by 200:

```
var tests = [
{value: 1723, expect: 1800},
{value: 1402, expect: 1600},
{value: 21, expect: 200},
{value: 17659, expect: 17800}
];
tests.forEach(test);
function test(entry) {
var result = Math.ceil(entry.value / 200) * 200;
console.log({
value: entry.value,
expect: entry.expect,
result: result
});
}
```

If you really want to work by rounding up to the "next 100," then the result for 1723 must be 1900 if the result for 1402 is 1600, and you do it by dividing by 100, rounding up, multplying by 100, and adding 100 (or dividing by 100, rounding up, adding 1, and multiplying by 100, which is the same thing):

```
var tests = [
{value: 1723, expect: 1800},
{value: 1402, expect: 1600},
{value: 21, expect: 200},
{value: 17659, expect: 17800}
];
tests.forEach(test);
function test(entry) {
var result = Math.ceil(entry.value / 100) * 100 + 100;
console.log({
value: entry.value,
expect: entry.expect,
result: result
});
}
```

Source (Stackoverflow)