25

What's an efficient and hopefully elegant incantation to convert decimal[] to double[]? I'm working with some fairly large arrays.

2 Answers 2

55
double[] doubleArray = Array.ConvertAll(decimalArray, x => (double)x);
Sign up to request clarification or add additional context in comments.

2 Comments

Would this be faster than decimalArray.Select(d => (double)d).ToArray()?
@Tobias I was also interested, so I created some small tests and the answer to your question is yes but how much faster, it depends on those two types and also if you are in Debug or Release - for 20,000,000 decimals ConvertAll lasts in average 628ms in Debug and 245ms in Release and your method lasts 1015ms in Debug and 573ms in Release in average on my computer. ConvertAll also consumes less memory - it handled approx. 80,000,000 floats to doubles and your method only around 30,000,000 before System.OutOfMemoryException was thrown with the same settings. Tested on .NET 4.5
3

You also can use and extension classes similar to this one

public static class ArrayExtension
{

   public static double[] ToDouble(this float[] arr) => 
                                    Array.ConvertAll(arr, x => (double)x);

}

Then:

double[] doubleArr = decimalArr.ToDouble();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.