Float to int

hi all
if i have array c = [1.0, 2.0, 2.0, 1.0] and i want to convert it to Int in this way c = [1,2,2,1]
i tried some thing like that

for i in count
     i = Int64(i) 
     println(i) # the output her is 1 then 2 => like what i need 
end

println(count) # the output her is in float64 it didn't change

how i can solve that ?

and one more thing please

and if i need to Define an array
how i can do that ?
Suppose i need array with size 26

You cannot convert an array inplace, but you could just do c = Int.(c) to assign a new array of Ints to c.

5 Likes

You can solve this with broadcast

c = [1.0, 2.0, 2.0, 1.0]
println(typeof(c))

c = Int.(c) #Change from Float to Int
println(typeof(c))

The dot between Int and c tells Julia to apply the Int conversion elementwise to the array.

Can you be more specific with what you are looking for for an array? If you are just looking to allocate space for a 26 element vector, you can do that by:
Array{Any, 1}(undef, 26)

The Any tells Julia the type of the Array, the 1 tells Julia the dimension of the matrix(above gives you a vector), and undef would allocate the space, but not populate it with anything.

1 Like

it was wonderful if it work

i tried this and their is an error (from REPL)

error during bootstrap:
LoadError("main.jl", 1, MethodError(Array{Any,1}, (Int64, 4), 0x0000000000006890))

this work

household = Array{Int64}(undef,length(a),1)

thanks

You don’t want the 1 there probably. That would create a n x 1 matrix, and you probably want a vector instead.

3 Likes

or


julia> c = [1.0, 2.0, 2.0, 1.0]
4-element Array{Float64,1}:
 1.0
 2.0
 2.0
 1.0

julia> cints = map(Int, c)
4-element Array{Int64,1}:
 1
 2
 2
 1
2 Likes