Convert an array into Int

Hi,

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

Thanks!

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.

Examples
≡≡≡≡≡≡≡≡≡≡

julia> convert(Int, 3.0)
3

julia> convert(Int, 3.5)
ERROR: InexactError: Int64(3.5)
Stacktrace:
[…]

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])
end

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]
1.0

julia> convert(Int, aux[1])
1

julia> aux[1]
1.0

This documentation might help
https://docs.julialang.org/en/v1/manual/conversion-and-promotion/

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).

2 Likes

Thank you!