ruby · level 2 · unit 3 · lesson 2
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
fills a pattern with values, neatly.
Money needs two decimal places, but Ruby shows two pounds fifty as 2.5. will round a float to two places, and .to_f converts a string like "3.75" into a float.
For full control, use format. Give it a pattern with placeholders, then the values to drop in, in order. %s takes any value as text, %d a whole number, and %.2f a float shown with exactly two decimal places.
third = 10.0 / 3
puts third
puts third.round(2)
puts "3.75".to_f + 1
puts format("%s owes £%.2f", "Sam", 2.5)
puts format("%d items", 3) .round(2) gives a number, but format gives a string, so use format when you show money.
guess first
Pounds and pence. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
price = 4.5
puts price
puts format("£%.2f", price)
puts format("%d tickets", 3)
your turn
Your turn. Split the bill.
Fill in the bill total in pounds and how many friends are sharing it, then press run.
fix it
The receipt lost its pence. Can you fix it?
- The pence have vanished. Which placeholder is in the pattern?
%dis for whole numbers, so it drops everything after the decimal point.- Change %d to %.2f inside the pattern, then press run.
nailed it
your numbers look like money now. :D
.round(2)rounds a float to two decimal places.formatfills placeholders in a pattern, in order.%.2falways shows exactly two decimal places.
new words in your collection
- round
- format
- placeholder
This lesson isn’t saved. A free account remembers every lesson you finish.