-1

I have multiple double values that need to be converted into a float array or int array, what should I do?

E.g.

double[] values= new double[]{123.456,234.123};
float[] floatValues=xxxx(values);
2
  • var floatValues = values.Cast<float>() ? What are the results here. You can just say i want to smash a big object into a little object and not care whats missing Commented Nov 2, 2021 at 3:39
  • Does this answer your question? C# Cast Entire Array? or convert Decimal array to Double array Commented Nov 2, 2021 at 4:05

3 Answers 3

3

You'll have to do it element-wise. There are multiple ways to achieve that.

  1. You could foreach over the source array like

     floatvalues = new float[values.Length];
     for(var i = 0;i < values.Length;++i)
         floatValues[i] = (float)values[i];
    
  2. You could use LINQ for simplifying the loop

     floatValues = values.Select(d => (float)d).ToArray();
    
  3. You can use Cast<T>()

     floatValues = values.Cast<float>().ToArray();
    
Sign up to request clarification or add additional context in comments.

Comments

3

Alternet way is to use Array.ConvertAll(),

Converts an array of one type to an array of another type.

float[] floatValues = Array.ConvertAll(values, float.Parse);

1 Comment

The converter should be Convert.ToSingle instead of float.Parse.
1

You can easily do this with Linq:

using Sytem.Linq;

double[] values= new double[]{123.456,234.123};
float[] floatValues= values.Cast<float>().ToArray();

1 Comment

Unable to cast object of type 'System.Double' to type 'System.Single'.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.