Basic data types

Introduction to Julia

James Fulton

Climate informatics researcher

Types of data

Integers are whole numbers

# This is stored as an integer
x_int = 1

# Print the type of x_int println(typeof(x_int))
Int64

Floats are numbers with a decimal point

# This is stored as a float
x_float = 1.0

# Print the type of x_float println(typeof(x_float))
Float64
Introduction to Julia

Other basic data types

Booleans

x_bool = true # or false

# Print the type of x_bool println(typeof(x_bool))
Bool

Strings

x_string = "Hello there"

# Print the type of x_string println(typeof(x_string))
String
  • Must use "..."
  • Cannot use '...'
Introduction to Julia

Other basic data types

Characters

x_char = 'A'

# Print the type of x_char println(typeof(x_char))
Char
  • Cannot have character 'AB'
  • Only 'A' or 'B', etc.
Introduction to Julia

Consequences of data types

# Bank balance as integer
balance = 100


# Interest rate as float interest_rate = 1.05
new_balance = balance * interest_rate
println(new_balance) println(typeof(new_balance))
105.0
Float64
# Bank balance as string
balance = "$100"

# Interest rate as string
interest_rate = "5%"

new_balance = balance * interest_rate


println(new_balance) println(typeof(new_balance))
$1005%
String
Introduction to Julia

Consequences of data types

# Bank balance as integer
balance = 100

# Interest rate as string
interest_rate = "5%"

new_balance = balance * interest_rate
ERROR: MethodError: 
no method matching *(::Int64, ::String)
Introduction to Julia

Converting between types

# Convert the integer x to float y
x = 1

y = Float64(x)
println(typeof(y))
Float64
# Convert the float x to integer y
x = 1.0
y = Int64(x)


println(typeof(y))
Int64
Introduction to Julia

Converting between types

# Convert the float x to integer y

x = 1.01
y = Int64(x)
ERROR: InexactError: Int64(1.01)
# Convert the float x to integer y
x = 1.0
y = Int64(x)


println(typeof(y))
Int64
Introduction to Julia

Converting between types

# Convert the integer x to string y
x = 1
y = string(x) # y = "1"

println(typeof(y))
String
# Convert the string x to integer y
x = "1"
y = parse(Int64, x) 

println(typeof(y))
Int64
Introduction to Julia

Converting between types

# Convert the integer x to string y
x = 1
y = string(x) # y = "1"

println(typeof(y))
String
# Convert the string x to float y
x = "1.0"

y = parse(Float64, x)
println(typeof(y))
Float64
Introduction to Julia

Summary of conversions

  • Use typeof(x) to find the type of x
  • Convert between data types using:
From To Function
Integer Float Float64(x)
Float Integer Int64(x)
Integer or float String string(x)
String Float parse(Float64, x)
String Integer parse(Int64, x)
Introduction to Julia

Let's practice!

Introduction to Julia

Preparing Video For Download...