Skip to content
Tutorials Center
My learning

Topics

Lesson 6 of 37 ยท Syntax and Types

Numbers and Math

Learn Crystal numeric types (Int8 to Int128, UInt, Float32, Float64), literals, division rules, overflow behaviour, conversions and the Math module, with read-only code and runnable Ruby stand-ins.

Crystal has a family of fixed-size numeric types, chosen at compile time, rather than one flexible number type. This is part of why it is fast: the compiler knows exactly how many bytes a number takes and which machine instruction to use. This lesson covers the types, literals, the arithmetic operators, what happens on overflow, converting between types and the Math module.

Crystal listings are read-only here. The Ruby stand-ins run on Ruby 4.0, whose Integer has no fixed size, so we point out where numbers behave differently.

Integer types

Type Size Range
Int8 8 bits -128 to 127
Int16 16 bits -32,768 to 32,767
Int32 32 bits about -2.1 billion to 2.1 billion
Int64 64 bits about +-9.2 quintillion
Int128 128 bits very large
UInt8, UInt16, UInt32, UInt64, UInt128 same sizes 0 up to twice as high

A plain integer literal like 42 is an Int32. If the number is too big for Int32, the literal becomes Int64 automatically. You can pick a type with a suffix:

CRYSTAL
a = 42          # Int32
b = 42_i64      # Int64
c = 255_u8      # UInt8
d = 1_000_000   # underscores make big numbers readable (Int32)
e = 0xFF        # hexadecimal, 255
f = 0b1010      # binary, 10
g = 0o17        # octal, 15

Use Int32 as the everyday default, Int64 for sizes, timestamps and IDs that may be large, and UInt8 for bytes.

Floating-point types

Float64 is the default for literals with a decimal point or exponent. Float32 uses half the memory with lower precision.

CRYSTAL
x = 3.14        # Float64
y = 2.5_f32     # Float32
z = 1.5e3       # Float64, 1500.0
puts 0.1 + 0.2  # 0.30000000000000004

The last line is not a Crystal bug: binary floating point cannot represent 0.1 exactly. The same happens in every language. For money use integers (cents) or a decimal library such as BigDecimal from the standard library.

Arithmetic

The usual operators are + - * / % ** and the unary minus.

CRYSTAL
puts 7 + 3      # 10
puts 7 - 3      # 4
puts 7 * 3      # 21
puts 7 / 2      # 3.5   (floating-point division in Crystal 1.x)
puts 7 // 2     # 3     (floor division)
puts -7 // 2    # -4    (rounds toward negative infinity)
puts 7 % 3      # 1     (remainder with the sign of the divisor)
puts 2 ** 10    # 1024

Two points matter for newcomers and for Ruby users:

  • / between integers gives a Float64 in current Crystal, while // gives the floor-divided integer. Ruby's / on integers does the floor division, so code ported from Ruby can behave differently. Always check division when porting.
  • Division by zero: 1 // 0 raises DivisionByZeroError at run time; 1.0 / 0 gives Infinity.

Here is a Ruby stand-in for the operators that behave the same in both languages, and where Ruby differs:

Ruby Stand-in: arithmetic in Ruby

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Ruby has no // operator (it would start a regular expression), so the stand-in uses div to show the floor-division result.

Overflow

A fixed-size integer can run out of room. Crystal does not silently wrap around by default: ordinary arithmetic on integers raises OverflowError at run time.

CRYSTAL
big = Int32::MAX        # 2147483647
big + 1                 # Unhandled exception: Arithmetic overflow (OverflowError)

If you really want wrapping, use the wrapping operators, which start with &:

CRYSTAL
puts Int32::MAX &+ 1    # -2147483648
puts 200_u8 &+ 100_u8   # 44
puts 5_u8 &- 10_u8      # 251

Wrapping arithmetic is common in hashes, checksums and random-number generators. For everything else, the default error is a feature: it turns a silent wrong answer into a visible failure.

Ruby never overflows, because Integer grows as needed. The stand-in below shows what the numbers would be if they wrapped to 32 bits, by hand:

Ruby Stand-in: simulating 32-bit wrap-around

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Converting between types

There are no automatic conversions that could lose information. You convert on purpose with to_* methods:

CRYSTAL
n = 42
puts n.to_f          # 42.0
puts 3.99.to_i       # 3    (truncates)
puts 3.99.round      # 4.0
puts 65.chr          # A
puts n.to_s          # "42"
puts "123".to_i      # 123
puts "12x".to_i?     # nil  (the ? version returns nil instead of raising)
puts "abc".to_i      # raises ArgumentError

to_i raises if the text is not a number; to_i? returns nil, which you then handle (see union types and nil). Mixing sizes in an operation is allowed when no information is lost: an Int32 + Int64 gives an Int64. Converting down, such as to_i32, raises if the value does not fit, and to_i32! wraps without checking.

The Math module

CRYSTAL
puts Math.sqrt(16)       # 4.0
puts Math.pow(2, 8)      # 256.0
puts Math::PI            # 3.141592653589793
puts Math.sin(Math::PI / 2)   # 1.0
puts Math.log(Math::E)   # 1.0
puts Math.max(3, 9)      # 9
puts 10.0.floor          # 10
puts 7.3.ceil            # 8
puts -3.abs              # 3

Math.sqrt always returns a Float64. Random numbers come from rand: rand(10) is an integer from 0 to 9, rand a float from 0 up to 1.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What type does the literal 42 have?

    Integer literals are Int32 unless they are too large or have a suffix.
  2. 2. What does Int32::MAX + 1 do in Crystal?

    Ordinary arithmetic is checked. Use &+ if you want wrapping.
  3. 3. Which operator performs floor division on integers?

    // is floor division. / between integers gives a Float64 in Crystal 1.x.
  4. 4. What does "12x".to_i? return?

    The ? version returns nil when the whole string is not a valid number.

Summary

  • Numbers have fixed sizes: Int8..Int128, UInt8..UInt128, Float32, Float64; the defaults are Int32 and Float64.
  • Use suffixes such as _i64 and _u8, and underscores for readability.
  • / is float division on integers, // is floor division.
  • Overflow raises an error; the &+ &- &* operators wrap on purpose.
  • Convert explicitly with to_i, to_f, to_s; use the ? forms when parsing may fail.

Next: Strings, Chars and Symbols