Numbers & Math
Reviewed & published by Brayan K
Ruby is a dynamic, beginner-friendly programming language, and numbers power nearly every program — from totals and counters to prices and percentages.
Part of the free Ruby course at LearnCodingFast — hands-on lessons with worked examples and the output they print, plus practice exercises and a quick quiz.
By the end of this lesson you'll do arithmetic, understand the Integer-vs-Float trap, and use the numeric methods Ruby gives every number.
What You'll Learn in This Lesson
- The arithmetic operators: + - * / ** %
- Why integer division truncates and how to avoid it
- Order of operations and using parentheses
- Numeric methods: even?, abs, round, floor, ceil
- Converting with to_i and to_f
- When Float precision matters (and what to do)
1️⃣ Arithmetic and the Division Trap
Ruby's arithmetic operators look familiar: + - * /, plus ** for exponent and % for the remainder. The one surprise is division: when both sides are Integers, Ruby throws away the fraction. Make one side a Float to keep the decimals.
# Ruby has two main number types: Integer (whole) and Float (decimal).
puts 7 + 3 # -> 10 addition
puts 7 - 3 # -> 4 subtraction
puts 7 * 3 # -> 21 multiplication
puts 7 ** 2 # -> 49 exponent (7 squared)
puts 7 % 3 # -> 1 modulo (remainder)
# WATCH OUT: integer ÷ integer truncates to an integer!
puts 7 / 3 # -> 2 (NOT 2.333...)
puts 7.0 / 3 # -> 2.3333333333333335 (a Float keeps the decimals)
puts 7 / 3.0 # -> 2.3333333333333335
# Order of operations follows normal math (use () to be explicit).
puts 2 + 3 * 4 # -> 14
puts (2 + 3) * 4 # -> 20That 7 / 3 == 2 result trips up nearly every beginner. Remember: a Float anywhere in the division "infects" the result with decimals.
2️⃣ Numeric Methods
Because numbers are objects, they carry useful methods. You'll reach for round, floor, and ceil for rounding, even?/odd? for tests, and abs for absolute value. Note to_i truncates rather than rounds.
# Numbers are objects, so they have handy methods.
puts 10.even? # -> true
puts 7.odd? # -> true
puts (-5).abs # -> 5 absolute value
puts 3.7.round # -> 4 nearest integer
puts 3.7.floor # -> 3 round down
puts 3.2.ceil # -> 4 round up
puts 3.14159.round(2) # -> 3.14 round to 2 decimals
# Convert between types
puts 9.to_f # -> 9.0
puts 9.9.to_i # -> 9 (truncates, does not round)
# Useful constants and helpers
puts 10.gcd(15) # -> 5 greatest common divisor
puts 17.to_s(2) # -> 10001 (17 in binary)Your turn. Split a bill with a tip among friends. Replace the three TODO values — keep total and tip as Floats so cents survive — then run it.
# 🎯 YOUR TURN — replace each ___, then run with: ruby bill.rb
# Split a restaurant bill among friends with a tip.
total = ___ # 👉 replace ___ with 86.50
people = ___ # 👉 replace ___ with 4
tip = ___ # 👉 replace ___ with 0.18 (18% as a fraction)
# 1) Add the tip to the total
with_tip = total + (total * tip)
# 2) Divide by the number of people (use a Float to keep cents!)
per_person = with_tip / people
# 3) Print the result rounded to 2 decimal places
puts "Each person pays: $#{per_person.round(2)}"
# ✅ Expected output (for 86.50, 4 and 0.18):
# Each person pays: $25.52Mini-Challenge: A Temperature Converter
Convert Celsius to Fahrenheit, remembering to use Floats in the formula. Run it with ruby temp.rb.
# 🎯 MINI-CHALLENGE: a temperature converter.
# Save as temp.rb and run with: ruby temp.rb
#
# 1. Store a Celsius temperature as a Float, e.g. 25.0
# 2. Convert to Fahrenheit: F = C * 9.0 / 5.0 + 32
# (use 9.0/5.0 so you keep the decimals!)
# 3. Round to 1 decimal place.
# 4. Print a sentence with both values.
#
# ✅ Example output:
# 25.0°C is 77.0°F
# your code hereCommon Errors (and the fix)
- Unexpected integer division — 1 / 2 is 0. Use 1.0 / 2 for 0.5.
- to_i rounds? No — it truncates — 9.9.to_i is 9. Use round if you want 10.
- "divided by 0" (ZeroDivisionError) — Integer division by zero raises an error. Check the divisor first, or use Floats where 1.0/0 gives Infinity.
- Adding a string and a number — "5" + 1 errors. Convert with "5".to_i + 1.
- Float surprises — 0.1 + 0.2 isn't exactly 0.3. Round for display, or use cents/BigDecimal for money.
Pro Tips
- 💡 Underscores in big numbers: write 1_000_000 for readability — Ruby ignores the underscores.
- 💡 fdiv for safe division: 7.fdiv(3) always returns a Float, no Float conversion needed.
- 💡 Random numbers: rand(6) gives 0–5; rand(1..6) rolls a die.
📋 Quick Reference — Numbers & Math
| Concept | Ruby Syntax |
|---|---|
| Exponent / modulo | 2 ** 8 / 7 % 3 |
| Float division | 7.0 / 3 |
| Round to n places | x.round(2) |
| Floor / ceil | x.floor / x.ceil |
| Even? / abs | n.even? / n.abs |
| Random | rand(1..6) |
🎉 Lesson Complete!
- ✅ Ruby has Integers (whole) and Floats (decimal)
- ✅ Operators: + - * / ** %
- ✅ Integer ÷ Integer truncates — use a Float to keep decimals
- ✅ Numbers have methods: round, floor, ceil, even?
- ✅ Watch Float precision for money; round or use cents
Practice quiz
What does 7 / 3 evaluate to in Ruby?
- 2.33
- 3
- 2
- 2.0
Answer: 2. Integer divided by Integer truncates the fraction, so 7 / 3 is 2.
What does 7.0 / 3 evaluate to?
- 2.3333333333333335
- 2
- 2.0
- 3
Answer: 2.3333333333333335. Making one side a Float keeps the decimals: 7.0 / 3 is about 2.333.
What does 7 % 3 return?
- 2
- 0
- 2.33
- 1
Answer: 1. % is modulo (remainder). 3 goes into 7 twice with 1 left over.
What does 2 ** 8 evaluate to?
- 16
- 256
- 64
- 10
Answer: 256. ** is exponentiation, so 2 ** 8 is 256.
What does 9.9.to_i return?
- 9
- 10
- 9.9
- 9.0
Answer: 9. to_i truncates toward zero, it does not round, so 9.9.to_i is 9.
What does 3.7.round return?
- 3
- 3.7
- 4
- 3.0
Answer: 4. round goes to the nearest integer, so 3.7.round is 4.
What does 3.2.ceil return?
- 3
- 4
- 3.2
- 3.0
Answer: 4. ceil always rounds up, so 3.2.ceil is 4.
Which method always returns a Float result for division?
- div
- quo
- to_i
- fdiv
Answer: fdiv. 7.fdiv(3) always returns a Float, no manual conversion needed.
What does 17.to_s(2) produce?
- "17"
- "10001"
- "11"
- "0x11"
Answer: "10001". to_s(2) gives the base-2 (binary) string, and 17 in binary is 10001.
Why can 0.1 + 0.2 not equal exactly 0.3 in Ruby?
- Ruby has a bug
- Integers overflow
- Floats use binary floating point with tiny rounding errors
- + is overloaded incorrectly
Answer: Floats use binary floating point with tiny rounding errors. Floats are binary floating point, so some decimals can't be represented exactly.
Continue this course
- Previous: Strings & Symbols
- Next: Control Flow — Make decisions with if, unless, case, and ternary expressions
- Quick reference: Ruby cheat sheet
Frequently asked questions
Why does 7 / 3 give 2 instead of 2.33 in Ruby?
When both operands are Integers, Ruby performs integer division and discards the fractional part, so 7 / 3 is 2. This is deliberate and matches many languages. To keep the decimals, make at least one side a Float: 7.0 / 3 or 7 / 3.0 both give roughly 2.333. A common real-world bug is dividing two integers (like cents or counts) and being surprised by a truncated result — convert to Float first when you need precision.
What is the modulo operator % used for?
The % operator returns the remainder after division. 7 % 3 is 1 because 3 goes into 7 twice with 1 left over. It's incredibly useful: n % 2 == 0 tests whether n is even, index % length wraps around a collection, and seconds % 60 gives the leftover seconds. Whenever you need 'cycling' or 'is divisible by' logic, modulo is the tool.
What's the difference between round, floor, and ceil?
round goes to the nearest integer (3.4 → 3, 3.6 → 4), and you can pass a number of decimal places, like 3.14159.round(2) → 3.14. floor always rounds down toward negative infinity (3.9 → 3), and ceil always rounds up (3.1 → 4). Note that to_i is different again: it simply truncates toward zero, so 9.9.to_i is 9, not 10.
Should I worry about Float precision in Ruby?
Sometimes. Floats use binary floating point, so values like 0.1 + 0.2 can produce 0.30000000000000004 — tiny rounding errors inherent to the format, not a Ruby bug. For everyday math this is fine. For money or anything requiring exactness, use the BigDecimal class or work in integer cents (e.g. store $1.99 as 199) to avoid the rounding entirely.