Convert an array into Int


If I have an 2D array of multiple elements (named aux), how do I convert or ensure that they are integers? Also note that I didn’t create this array, it was copied from a dataframe, which was in turn taken from a CSV file. I don’t know if that is relevant but thought it might be better to mention. I tried round(Int, aux) but it doesn’t work. I get the following error:

ERROR: MethodError: objects of type Array{ConstraintRef{Model,C,Shape} where Shape<:AbstractShape where C,1} are not callable
Use square brackets [] for indexing an Array.

Here’s an MWE

df2 = DataFrame(csv2)
aux = df2.T


Try using the convert function

convert(T, x)

Convert x to a value of type T.

If T is an Integer type, an InexactError will be raised if x is not representable by T, for example if x is not
integer-valued, or is outside the range supported by T.


julia> convert(Int, 3.0)

julia> convert(Int, 3.5)
ERROR: InexactError: Int64(3.5)

If T is a AbstractFloat or Rational type, then it will return the closest value to x representable by T.

1 Like

Thanks for the suggestion, but it doesn’t accept arrays apparerntly. So I tried using a for loop

for i = 1:100 
     convert(Int, aux[i])

I think it momentarily converts to integer but then it goes back to float. The entire array is actually integer except for one value, because I wanted to experiment. But because of that one float value, the entire array becomes float.

julia> aux[1]

julia> convert(Int, aux[1])

julia> aux[1]

This documentation might help

The element type of an array is fixed and cannot be changed. You can create a new array with the result of converting all elements to Int with e.g. Int.(aux).


Thank you!