Greg Gum
Greg Gum

Reputation: 37895

how to drop decimals after 3rd decimal

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.

Upvotes: 0

Views: 201

Answers (5)

Sebastien H.
Sebastien H.

Reputation: 7136

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);

Upvotes: 0

BRAHIM Kamel
BRAHIM Kamel

Reputation: 13755

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(); 

Upvotes: 3

D Stanley
D Stanley

Reputation: 152521

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");

Upvotes: 0

Aftab Ahmed
Aftab Ahmed

Reputation: 1737

try this

double d= yourNum;
String s=d.ToString("0.00");

Upvotes: 0

Sudhakar Tillapudi
Sudhakar Tillapudi

Reputation: 26209

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

Upvotes: 1

Related Questions