Math.Round issue

I am trying to do some simple rounding with a precision of 1. For some reason, the only way I found that I was able to do this, is by using the following lines:

double temp = tbJointServo.Value / 10.0;
string tempS = temp.ToString(".#");
temp = Convert.ToDouble(tempS);
txtJointServo.Text = tempS;

Where "tbJointServo" has a minimum value of 0 and a maximum value of 3600.

Is there any better way to accomplish this I've tried using:

Math.Round(((double)(tbJointServo.Value / 10.0)), 1)

Which doesn't give me a precision of 1 like I wanted. I'm sure this is probably some C# thing, as I'm a native VB.NET programmer.



Answer this question

Math.Round issue

  • Rocky Raher

    What's the significant difference between the two


  • Brad007

    Thanks for the lesson:)


  • JulieL

    The internal storage is different. A double is a floating point, and floats are never exactly accurate.

    Check the MSDN docs for more details.

    For instance, try this:

    double number = 6;
    double divider = 0;

    decimal decNumber = 6;
    decimal decDiv = 0;

    MessageBox.Show ((number / divider).ToString());
    MessageBox.Show ((decNumber / decDiv).ToString());

    As you can see, the first division does not throw an Exception, since the zero is not a real zero. It can be something like 0.00...01, while with the decimal, it is realy a zero, so the second division does throw an exception.


  • Piyu

    If you really want perfect precision, you should use a decimal, and not a double.


  • Math.Round issue