Ruby Numbers
Numbers in Ruby are values used for counting and maths. Ruby works with whole numbers and with numbers that have a decimal point.
Integers and floats
An integer is a whole number with no decimal point. A float is a number with a decimal point.
puts 17
puts 2.5Two kinds of division
Dividing two integers drops the fraction part. Making one value a float keeps the fraction part.
puts 7 / 2
puts 7.0 / 2Remainders and negative division
The % sign finds what is left after division. Division with a negative integer rounds down to the lower whole number.
puts 7 % 2
puts -7 % 2
puts -7 / 2Floats up close
Floats hold decimal values in a close stored form. Adding 0.1 and 0.2 shows the small gap.
puts 0.1 + 0.2Big numbers with underscores
Underscores split a long number into groups. The printed value has no underscores.
puts 1_000_000Example
puts 12 + 8
puts 7 / 2
puts 7.0 / 2
puts 10 % 3
puts 1_500 + 500Key points
- Use + to add, - to take away, * to multiply and / to divide.
- Integer division drops the fraction part of the answer.
- Float division keeps the fraction part of the answer.
- The % sign gives the remainder after a division.
- Negative integer division rounds the answer down.
- Underscores can split a long number into groups that are easy to read.
In this example, the first line adds 12 and 8 and prints 20. The second line divides two integers and prints 3. The third line divides with a float and prints 3.5. The fourth line prints the remainder of 10 divided by 3. The last line adds two grouped numbers and prints 2000.
Note
A float keeps a close stored value, not an exact decimal value.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does puts 7 / 2 print?