Re: rounding
- From: "Peter Duniho" <NpOeStPeAdM@xxxxxxxxxxxxxxxx>
- Date: Mon, 04 Jun 2007 12:25:23 -0700
On Mon, 04 Jun 2007 11:54:43 -0700, Nicholas Paldino [.NET/C# MVP] <mvp@xxxxxxxxxxxxxxxxxxxxxxxxxxx> wrote:
You have to explain how the first and last cases are supposed to work. Rounding .5625 to two places should result in .57 and rounding 6.125 to two places should result in 6.13, using mathematical rounding.. What rounding are you doing?
It seems to me that he wants the rounding to round to multiples of 0.05.
To the OP, you can accomplish this in the specific case like this:
double RoundToFiveHundredths(double num)
{
return Math.Round(num * 2.0, 1) / 2.0;
}
Assuming you are always dealing with multiples that are themselves divisible into 1.0, you can do it generally like this:
double RoundToMultiple(double num, double multiple)
{
double scale = 1.0 / multiple;
return Math.Round(num * scale) / scale;
}
Note that if you pick something that is theoretically divisible into 1.0, but which is not representable in binary (eg 1/3, or 0.333...), you may wind up wind rounding error. But this would be unavoidable, since even if rounded perfectly, you would not be able to represent the result exactly in binary form (the same thing holds true for decimal types, though with different specific values of course).
Pete
.
- Follow-Ups:
- Re: rounding
- From: Nicholas Paldino [.NET/C# MVP]
- Re: rounding
- References:
- rounding
- From: abcd
- Re: rounding
- From: Nicholas Paldino [.NET/C# MVP]
- rounding
- Prev by Date: Re: lists of open ports
- Next by Date: programming .NET 2.0 windows appz, how???
- Previous by thread: Re: rounding
- Next by thread: Re: rounding
- Index(es):
Relevant Pages
|