Working with Numbers

Learn about the different types of numbers in Ruby.

We'll cover the following

Numbers

We can create a number by simply writing it out. The number 123 is Ruby code, representing the number 123. We can also use a . as a decimal point, for example, 12.34.

Negative numbers are created by prepending a minus sign (-). For example, -99 is the number -99.

We can also use an underscore (_) to improve readability when dealing with large numbers. For example, 100_000_00.23 is exactly the same number as 10000000.23. This usage is strictly optional, though.

Types of numbers

For technical reasons, there are actually different kinds of numbers, and each can have other sub kinds.

For example, there are Integer numbers, which are regular whole numbers, and depending on their size, there are two kinds of them. There are also other kinds, such as Float, Rational, Complex, and BigDecimal. We can safely ignore these for now.

However, the most useful distinction to bear in mind when we perform calculations with numbers is that Integer numbers (integers) and decimal point numbers (floating point numbers, or floats) are different.

If we perform a calculation that uses Integer numbers, we always get an Integer back:

Press + to interact
puts 1 + 2

However, if any of the numbers involved is a Float, then we get a Float back:

Press + to interact
puts 1.0 + 2
puts 1 + 2.0

Remember: Mathematical operations involving integers and floats result in a floating-point number, unless all numbers used are integers.

This is important when we perform division (/ means divide by), for example:

Press + to interact
puts 3 / 2

Notice that any decimal places are cut off because the result needs to be an Integer number.

However, if we use floats, the result is also a Float:

Press + to interact
puts 3.0 / 2
puts 3 / 2.0

Remember: Use floating-point (decimal) numbers when dividing.

When using these floating-point numbers with sensitive data, like data associated with currencies, we might want to use BigDecimal as an alternative to Float, which gives us more accurate results.