Vinoth Kumar C M
Vinoth Kumar C M

Reputation: 10598

Round off decimal value up to nearest 0.05 value?

I was reading How to round decimal value up to nearest 0.05 value?.

It mentions the following stuff.

   Math.ceiling(myValue * 20) / 20

How does this hack work ? I mean how did we arrive at this solution?

Upvotes: 2

Views: 4387

Answers (3)

Miki
Miki

Reputation: 7188

1/20 is 0.05

1/100 is 0.01

If you want to round to 0.01, you multiply by 100, round and divide by 100. Similarly, to round to 0.05, you do the same, but with 20.

Upvotes: 5

Konrad Garus
Konrad Garus

Reputation: 54035

There is no library function for rounding to 0.05, but there is one for rounding to 1.00: ceiling. That's almost (well, double isn't absolutely precise) the same as the formula that you pasted (20 * 0.05 = 1)

Did you try to substitute something for your formula and see what happens?

1.03 * 20 = 20.60
ceil(20.6) = 21
21/20 = 1.05

Upvotes: 4

ratchet freak
ratchet freak

Reputation: 48216

it maps 0.05 to 1 (by multiplication) inside the Math.ceiling function and then maps the result back to 0.05 (by division)

Upvotes: 0

Related Questions