How to change datatype like MATLAB

There are several floating point types in Julia.

  • single in MATLAB is the equivalent of Float32
  • double in MATLAB is the equivalent of Float64

Additionally, there are

  • Float16 sometimes called half
  • BigFloat arbitrary precision floating point
julia> subtypes(AbstractFloat)
4-element Vector{Any}:
 BigFloat
 Float16
 Float32
 Float64

julia> p = 22/7
3.142857142857143

julia> typeof(p)
Float64

julia> p32 = Float32(p)
3.142857f0

julia> typeof(p32)
Float32

julia> p16 = Float16(p)
Float16(3.143)

julia> typeof(p16)
Float16

The convert(Float32, p) example shown above is a more general way to do this for other types.

Note that if you have an array, you may want to use broadcasting to convert all elements of the array to the desired type.

julia> a = [1,2,3,4]
4-element Vector{Int64}:
 1
 2
 3
 4

julia> Float32.(a)
4-element Vector{Float32}:
 1.0
 2.0
 3.0
 4.0

There are some related types.

  • Rational used to represent a number that is the quotient of two integers.
  • Irrational used to represent a number that cannot be expressed as a quotient of two integers

The method float can be used to convert them to some kind of floating point value.

julia> r = 22//7
22//7

julia> typeof(r)
Rational{Int64}

julia> float(r)
3.142857142857143

julia> typeof(ans)
Float64

julia> pi
π = 3.1415926535897...

julia> typeof(pi)
Irrational{:π}

Floating point can yield some strange results:

julia> 0.1 + 0.2
0.30000000000000004

julia> big"0.1" + big"0.2"
0.3000000000000000000000000000000000000000000000000000000000000000000000000000017

julia> typeof(ans)
BigFloat

You can use rationals to help:

julia> 1//10 + 2//10
3//10

julia> float(ans)
0.3

There are some additional packages that can help:

julia> using FixedPointDecimals

julia> FixedDecimal{Int, 1}(0.1) + FixedDecimal{Int, 1}(0.2)
FixedDecimal{Int64,1}(0.3)

julia> float(ans)
0.3
4 Likes