How to convert a float array to an integer array in Julia
An array is an ordered collection of heterogeneous elements in Julia. Arrays are mutable data types, elements in the arrays can be added, removed, or modified. Unlike sets, arrays can store duplicate elements as well.
We will use list comprehension to traverse the array and to convert each float number to an integer using the floor() function. Once we traverse all numbers we will get a new array of integers.
Problem Statement
Input_Array = [1.5, 2.8, 9.7]
Output_Array = [1, 2, 9]
Syntax
[ floor(Int,x) for x in array_of_float_numbers]
Parameters
x: Specified value.
Return value
In Julia, the floor() method is used to return the nearest integral number that is less than or equal to the supplied value. It returns the floor of a float value provided to it. The return value has a data type of the first parameter of the floor function.
Let us take a look at an example of floor() function.
Example
#given float arrayfloat_array = [1.5, 2.8, 9.7]#convert float to int arrayint_array = [floor(Int,x) for x in float_array]#display the int arrayprintln(int_array)
Explanation
Line 2: We declare and initialize a variable
float_arraywith an array of floating numbers.Line 5: We will use list comprehension to traverse the
float_arrayand apply afloor()function to each float number to convert it to an integer number. We will assign the returned array to a variableint_array.Line 8: We will display the new array of integers
int_array.
Free Resources