🎓 A1Learner
🔍
0 of 52 lessons completed

Julia Type Conversions

A type conversion is a change that turns a value of one type into a value of another type. Julia has a separate tool for each common change.

parse reads a number from text

The text "42" becomes the number 42. Adding 8 then works as arithmetic.

number = parse(Int, "42")
println(number + 8)

string, float and Int change the type

Text can join with other text using *. A decimal point shows in the float result.

println(string(42) * "!")
println(float(3))
println(Int(3.0))
println(Int('A'))

Four tools round in four ways

Each tool takes a decimal number and gives a whole number. The results show the cut, nearest, lower and higher choices.

println(trunc(Int, 3.9))
println(round(Int, 3.6))
println(floor(Int, 3.9))
println(ceil(Int, 3.1))

Example

text = "17"
number = parse(Int, text)
println(number * 2)
println(string(number) * " points")
println(float(number))
println(round(Int, 17.6))

Key points

  • parse: a function that reads text and builds a number from it.
  • Direct call: Int("42") does not work because a type name cannot read text.
  • string: a function that turns a value into text.
  • float: a function that turns a whole number into a decimal number.
  • Int: a call that turns a whole decimal value such as 3.0 into a whole number.
  • Rounding tools: trunc, round, floor and ceil each turn a decimal number into a whole number in a stated way.

In this example, parse first turns the text "17" into the number 17. The number is then doubled and also turned back into text for the label. The last two lines show the same value as a decimal number and rounded to a whole number.

Note

Int('A') is also a conversion and it gives the number code 65.

Try it Yourself

Edit the code, then press Run.

Running is simulated · JuliaHub

Exercise

Which call turns the text "42" into the number 42?