0

I have a UI control which is based on a double instead of an decimal.

When it should return a value of 0.001 it returns a value of 0.00100000004749745

How do I convert this to a decimal with the correct value of 0.001?

Note that I am not trying to format it as a string, just get the correct value.

Greg Gum
  • 33,478
  • 39
  • 162
  • 233
  • 4
    Your best bet is to start using decimal when you care about that precision. Powers of ten do not have simple representations in base-2. All of the conversions and rounding will result in error at some point. – n8wrl Feb 20 '14 at 15:41
  • I agree, but the control is based on a double and I cannot rewrite the control. Thus I am converting the number before actually using it. – Greg Gum Feb 20 '14 at 15:44

5 Answers5

3

just use Math.Round Method (Decimal, Int32)

            double d = 0.00100000004749745;
            double ma = Math.Round(d, 3);  
            //if you want it as a string 
            string s = ma.ToString(); 
BRAHIM Kamel
  • 13,492
  • 1
  • 36
  • 47
1
double d= 0.00100000004749745;
String s=d.ToString("N3");    //gives you 0.001
decimal dd=Convert.ToDecimal(s);//converts double value 0.001 into decimal
Sudhakar Tillapudi
  • 25,935
  • 5
  • 37
  • 67
0

try this

double d= yourNum;
String s=d.ToString("0.00");
Aftab Ahmed
  • 1,727
  • 11
  • 15
0

You're experiencing the fact that 0.1 cannot be stored exactly in a double.

If you just want to display the result in 3 decimals and not worry about the floating-point error just use:

string s = dec.ToString("0.000");
D Stanley
  • 149,601
  • 11
  • 178
  • 240
0

you can find a similar question already answered here using the String Format :

c# - How do I round a decimal value to 2 decimal places (for output on a page)

This can be a simple way to solve your problem using :

decimalVar.ToString ("#.###");

For more complex purposes this can be used if you want to keep working with a decimal value :

decimal.Round(yourValue, 3, MidpointRounding.AwayFromZero);
Community
  • 1
  • 1
Sebastien H.
  • 6,818
  • 2
  • 28
  • 36