-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);
Ethan
  • 876
  • 8
  • 18
  • 34
djc
  • 17
  • 5
  • `var floatValues = values.Cast()` ? 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 – TheGeneral Nov 02 '21 at 03:39
  • Does this answer your question? [C# Cast Entire Array?](https://stackoverflow.com/questions/2068120/c-sharp-cast-entire-array) or [convert Decimal array to Double array](https://stackoverflow.com/q/4175716/150605) – Lance U. Matthews Nov 02 '21 at 04:05

3 Answers3

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();
    
Tanveer Badar
  • 5,438
  • 2
  • 27
  • 32
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();
bolov
  • 72,283
  • 15
  • 145
  • 224
1

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);
Prasad Telkikar
  • 15,207
  • 5
  • 21
  • 44