I have a number like 6511 and I want to round it up to 7000. How do
I tell the computer to round the numbers to the thousands place. I
know how to round decimals but not whole numbers. Thanks for you
Please help!

Try

1000*((6511+500)\1000)

With a little playing around you should be able to roll your own Round function to round to an arbitrary digit.

@Reverend Jim: I'd also divide by 1000, round and then multiply by 1000, but I don't get why you are adding 500. Please explain.

You want all numbers (for example) from 6500 to 7499 to give you a result of 7000. If you don't add 500 to the number first then everything from 6500 to 6999 would give you 6000 as a result.

6512 + 500 = 7012    \ 1000 = 7    * 1000 = 7000   correct rounding
6512                 \ 1000 = 6    * 1000 = 6000   incorrect rounding

Would that not mess up when:

6312 + 500 = 6812 \ 1000 = 6 * 1000 = 6000
6312              \ 1000 = 6 * 1000 = 6000

Or am I just missing some language side rounding method?

Those are the correct results for rounding those numbers. Consider if you were using decimal numbers instead and rounding to the nearest whole number.

input      rounded
6.312      6.000
6.500      7.000

The easiest way to round is to add half the value you are rounding to, then truncate. If you are rounding (money) to the nearest cent then add half a cent and truncate. If you want to round to the nearest 1000 then add 500 and truncate.

I'd just use

Math.round(6512 /1000) * 1000

It will probably do the same, but I find it easier to understand when reading old code.

I prefer not to use Math.Round because of one peculiarity.

Math.Round(1.5) = 2.0
Math.Round(2.5) = 2.0

I believe that a rounding function should behave the same whether or not the integer part is even or odd. I was always taught that x.5 always rounds up to the next integer value.

Tangent: I also have a beef with the Random class. Random.Next(minvalue,maxvalue) according to the documentation at msdn.microsoft.com, returns "A 32-bit signed integer greater than or equal to minValue and less than maxValue". Sorry, but "maxvalue" by definition means "the maximum value you want returned". Microsoft should fix this or change the parameter name to maxvalueminusone. You can't just go redefining words as it suits you like Alice's caterpillar.

But I'm not bitter ;)`

Edited 4 Years Ago by Reverend Jim: n/a

This article has been dead for over six months. Start a new discussion instead.