Answered by:
How can i convert float to int?

float h[4] = {0.4830f, 0.8365f, 0.2241f, 0.1294f};
float g[4] = {h[3], h[2], h[1], h[0]};
int *yhigh = &yin[N/2];
int *ylow = yin;
I have this kind float, like in first line. how can i convert them in int? These are used in a calculation. Please help me.
Question
Answers

Russel81,
A float can be converted to int simply by casting:float z = 5.123f;
int a = (int) z;This will truncate the float. You can use several functions from Math (Math.Floor, Math.Ceiling, Math.Round) that will allow you to specify how to convert your floating point value to an integer. The result is still a floating point, so you will need the cast.
float z = 5.567f;
int a = (int) Math.Round (z);If you need to convert an entire array at a time, you might be better off using Array.ConvertAll<>.
HTH
mc 
Like he said, use Array.ConvertAll().
You can use it like this:
private static void Test()
{
float[] farray = { 1.0f, 1.4f, 1.5f, 1.6f };
int[] iarray1 = Array.ConvertAll<float, int>
(
farray,
new Converter<float, int>(FloatToInt)
);
}
private static int FloatToInt(float f)
{
return (int)Math.Floor(f+0.5);
}
You can also specify the conversion function "inline" using something called an "anonymous method". You would do that like this (split over several lines for readability):
int[] iarray2 = Array.ConvertAll<float, int>
(
farray,
new Converter<float, int>
(
delegate(float f)
{
return (int)Math.Floor(f+0.5f);
}
)
);
All replies

Russel81,
A float can be converted to int simply by casting:float z = 5.123f;
int a = (int) z;This will truncate the float. You can use several functions from Math (Math.Floor, Math.Ceiling, Math.Round) that will allow you to specify how to convert your floating point value to an integer. The result is still a floating point, so you will need the cast.
float z = 5.567f;
int a = (int) Math.Round (z);If you need to convert an entire array at a time, you might be better off using Array.ConvertAll<>.
HTH
mc 

Like he said, use Array.ConvertAll().
You can use it like this:
private static void Test()
{
float[] farray = { 1.0f, 1.4f, 1.5f, 1.6f };
int[] iarray1 = Array.ConvertAll<float, int>
(
farray,
new Converter<float, int>(FloatToInt)
);
}
private static int FloatToInt(float f)
{
return (int)Math.Floor(f+0.5);
}
You can also specify the conversion function "inline" using something called an "anonymous method". You would do that like this (split over several lines for readability):
int[] iarray2 = Array.ConvertAll<float, int>
(
farray,
new Converter<float, int>
(
delegate(float f)
{
return (int)Math.Floor(f+0.5f);
}
)
);