9 Conversion and promotion

 

This chapter covers

  • Conversion of one related type to another
  • How promotion finds the least common denominator among related types in an expression
  • Exploring the Julia standard library using the @edit macro

Julia and other mainstream programming languages handle arithmetic involving different number types so effortlessly that most of us likely don’t pay much attention to this fact:

julia> 3 + 4.2                    #1
7.2
 
julia> UInt8(5) + Int128(3e6)     #2
3000005
 
julia> 1//4 + 0.25
0.5

In reality, doing this involves quite a lot of complexity. Under the hood, most programming languages have defined a set of promotion rules, which say what should be done if you combine numbers of different types. Promotion rules make sure all the numbers are converted to a sensible common number type that can be used in the final calculation. Don’t confuse number conversion with parsing text strings to produce numbers.

You might wonder why you should care about these concepts. Mastering Julia’s promotion and conversion system opens the door to a deeper insight into how numbers work in Julia. That will make you capable of doing a wide variety of tasks, such as the following:

  • Defining custom number types
  • Defining a physical units system and performing conversions between different units

9.1 Exploring Julia’s number promotion system

9.2 Understanding number conversion

9.3 Defining custom units for angles

9.3.1 Defining angle constructors

9.3.2 Defining arithmetic operations on angles

9.3.3 Defining accessors to extract degrees, minutes, and seconds

9.3.4 Displaying DMS angles

9.3.5 Defining type conversions

9.3.6 Making pretty literals

9.3.7 Type promotions

Summary