rounding values to the nearest 5 or 10

  • Thread starter Thread starter Milsnips
  • Start date Start date
M

Milsnips

hi there,

any help with this one? i have say, numbers which i'd like to be rounded to
the nearest 5 or 10, example:

147.24 -->>150
181.99 -->> 180
824.18 -->>825
822.49 -->>820

and so on.. is there anything that i can do this right away in .net or would
i have to somehow create my own little rounding function for this?

thanks,
Paul
 
Milsnips said:
hi there,

any help with this one? i have say, numbers which i'd like to be rounded
to the nearest 5 or 10, example:

147.24 -->>150
181.99 -->> 180
824.18 -->>825
822.49 -->>820

and so on.. is there anything that i can do this right away in .net or
would i have to somehow create my own little rounding function for this?

The rounding function isn't hard.

static int round5(float x)
{
return (x % 5) >= 2.5 ? (int)(x / 5) * 5 + 5 : (int)(x / 5) * 5;
}

I count a worse case scenario of 5 cpu ops, which is probably a good deal
less than the stack frame cost.
 
hi there,
any help with this one? i have say, numbers which i'd like to be rounded to
the nearest 5 or 10, example:

147.24 -->>150
181.99 -->> 180
824.18 -->>825
822.49 -->>820

and so on.. is there anything that i can do this right away in .net or would
i have to somehow create my own little rounding function for this?

thanks,
Paul

Divide the value by five, round it to the nearest integer, then multiply
it by five.

Example:

double x = 147.24
int y = (int)Math.Round(x / 5.0) * 5;

(This will of course round the number to 145, not 150 as you used in
your example.)
 
yep, thats right, just what i was after! thanks alot.

regards,
Paul.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top