Double converstion help needed

• Question

• hello

I have a double variable

for example

Double data = 15.1234567891112436

Double data2  = Convert.ToDouble(String.Format("{0:n8}", data));  //here i am converting it to 8 digit

But if you see the code it i have a double variable which i will convert to string and then string to double "it will eat the performance "

what is the best way to do this?

It's Me
Monday, July 19, 2010 1:12 PM

• ```double number = 1.23456789012345678;
double n8 = Math.Round(number,8);

```

This may be better

• Proposed as answer by Monday, July 19, 2010 2:10 PM
• Marked as answer by Tuesday, July 20, 2010 4:55 AM
Monday, July 19, 2010 1:38 PM

All replies

• if you don't have too big numbers:

```double number = 1.23456789012345678;
double n8 = ((long)(number * 100000000)) /  (double) 100000000;
```
Monday, July 19, 2010 1:35 PM
• ```double number = 1.23456789012345678;
double n8 = Math.Round(number,8);

```

This may be better

• Proposed as answer by Monday, July 19, 2010 2:10 PM
• Marked as answer by Tuesday, July 20, 2010 4:55 AM
Monday, July 19, 2010 1:38 PM
• You are using String.Format to format a numeric to a string and then parsing the string back to a double.  These are not slow operations.  You should avoid using them in performance sensitive code.  Nevertheless the above code wouldn't even register on a profiler unless you called them in a loop.  There is other code that is far more expensive.  I'm not really sure what your question is?

Michael Taylor - 7/19/2010
http://msmvps.com/blogs/p3net

Monday, July 19, 2010 1:39 PM
• Why do you want to make it 8 digits? Just format the string when you display it, otherwise leave it with full precision.
Monday, July 19, 2010 2:01 PM
• Why do you want to make it 8 digits? Just format the string when you display it, otherwise leave it with full precision.
I think Volk is right and the OP is trying to round the number, and rather than using a numeric based rounding function he's converting it to a string to do it.
Monday, July 19, 2010 2:11 PM