Skip to content
AgileLogics
5 min read

Types and Conversion

Prerequisites: Numbers and arithmetic

Every value in Julia has a type. Variables don't — they're just names. Use typeof to ask, and isa to test:

println(typeof(1), " ", typeof(1.0), " ", typeof(true))
println(typeof("hi"), " ", typeof('h'), " ", typeof(nothing))
println(typeof([1, 2, 3]), " ", typeof(1:3))
println(1 isa Int, " ", 1 isa Float64, " ", 1 isa Number)
Int64 Float64 Bool
String Char Nothing
Vector{Int64} UnitRange{Int64}
true false true

Int is an alias for the machine's native integer (Int64 on 64-bit systems). Number is an abstract type that covers every kind of number — Level 2 explores the type hierarchy.

Converting between types

println(Float64(3))
println(Int(4.0))
println(round(Int, 4.7))
println(trunc(Int, 4.7))
println(parse(Int, "42") + 1)
println(parse(Float64, "2.5") * 2)
println(string(42) * "!")
println(tryparse(Int, "forty-two"))
3.0
4
5
4
43
5.0
42!
nothing
  • Float64(x), Int(x): convert between number types. Int(4.7) throws an InexactError because it would lose information — use round, trunc, floor, or ceil with a target type instead.
  • parse(Type, string) turns text into a number; tryparse returns nothing instead of throwing if the text isn't valid.
  • string(x) turns anything into a string. * joins strings (not +).

Mixed arithmetic

println(1 + 2.5)
println(typeof(1 + 2.5))
println(typeof(1 + 1//2))
println(true + true)
3.5
Float64
Rational{Int64}
2

When you mix types, Julia promotes them to a common type that can represent both. Bool is a number too: true is 1 and false is 0.

Common mistakes

  • Writing "Score: " + 10. There's no + for strings; use interpolation ("Score: $score") or string("Score: ", 10).
  • Calling parse(Int, "3.5") — that's not an integer, so it throws. Parse as Float64 first.