Rounding

W

Wayne Wengert

How do you round numbers in .NET? I have numbers defined as Single and after
some calculations I want to round the result to the nearest tenth so I can
do comparison of results (the rfuzz problem). Does FORMAT round?
 
J

Jon Skeet

Wayne Wengert said:
How do you round numbers in .NET? I have numbers defined as Single and after
some calculations I want to round the result to the nearest tenth so I can
do comparison of results (the rfuzz problem). Does FORMAT round?

If you want to compare results, then I suggest that rather than
rounding you just compare the difference between the expected results
and the ones you've got. You can specify the number of digits when you
format, but that'll use (I believe) bankers' rounding, which may or may
not be what you want.
 
P

Phil Price

Wayne said:
How do you round numbers in .NET? I have numbers defined as Single
and after some calculations I want to round the result to the nearest
tenth so I can do comparison of results (the rfuzz problem). Does
FORMAT round?

For rounding down:

System.Math.Floor(myNumber);
For rounding up:
System.Math.Ceiling(myNumber);
For simple rounding (the kind you do in maths classes at school):
System.Math.Round(myNumber);
Obviously these all return int types, and dont effect the parameter
variable.
Peace.
 
S

Steven Licciardi

If you multiply the number by 10e10 before you round (using the Math.Round
above, or just CInt(num), then divide by 10e10, this will give you 10
decimal places.

Steven
 
J

Jon Skeet

Phil Price said:
For simple rounding (the kind you do in maths classes at school):
System.Math.Round(myNumber);

No, that's *not* the kind of rounding most people do in maths classes
at school. At least, it certainly isn't the kind of rounding *I*
usually came across. It's bankers' rounding - halves round towards
even, so Math.Round(1.5)=2, Math.Round(2.5)=2, Math.Round(3.5)=4 etc.
 

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

Top