Re: rounding



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
.



Relevant Pages

  • Re: Round off
    ... rounding to two decimal places which necessarily gives a String. ... The OP asked about rounding a number to 2 decimals - not about converting it ... Number 3.5 is a multiple of ... FAQ 4.6 can be correspondingly changed. ...
    (comp.lang.javascript)
  • Re: [-mm PATCH] Memory controller improve user interface (v3)
    ... +Setting a limit to a number that is not a multiple of page size causes ... +rounding up of the value. ... A successful write to this file does not guarantee a successful ...
    (Linux-Kernel)
  • Re: Issues with rounding
    ... There's a huge body of literature out there on BIGNUM algorithms including issues of ... Certainly you can round the string representation. ... the position of the rounding digit. ... nearest whole number multiple of this unit. ...
    (microsoft.public.vc.mfc)
  • Re: Find Even Number
    ... let alone the wrong end of it! ... yields those lovely recurring digits 142857 which characterise all ... Multiply it by any multiple of 7 and it will yield an ... No other multipliers will do that exactly (though rounding ...
    (microsoft.public.excel.misc)
  • Re: rounding
    ... Rounding .5625 to two places should result in .57 and rounding ... It seems to me that he wants the rounding to round to multiples of 0.05. ... return Math.Round(num * scale) / scale; ... wind up wind rounding error. ...
    (microsoft.public.dotnet.languages.csharp)