Numbers with decimal points are floats (floating-point numbers). Computers store them in binary, and some decimals can't be stored exactly, leading to one of programming's most famous surprises.
EXAMPLE
loading editor…
YOUR TURN
Your turn → Make it print 0.3. In Python use round(0.1 + 0.2, 2). In JavaScript use Math.round((0.1 + 0.2) * 100) / 100.
loading editor…
Syntax has to be exact. Every quote, bracket and parenthesis needs its partner, and in Python the spaces at the start of a line count. One slip and the program won't run; the message will say where.
Compare → Python's round(value, places) returns a number. JavaScript's.toFixed(places) returns a STRING (notice the quotes if you check its type), a classic gotcha.
Now the real-world pattern you'll use forever, computing a total with tax:
EXAMPLE
loading editor…
YOUR TURN
Your turn → The community center's cut is 15% of the pre-tax subtotal. Add a line computing it, rounded to 2 places.
loading editor…
Syntax has to be exact. Every quote, bracket and parenthesis needs its partner, and in Python the spaces at the start of a line count. One slip and the program won't run; the message will say where.
◈ Graded Challenge
A vendor sold 23 jars of shea butter at 8.50 each. Create subtotal holding the takings, tax holding 7 percent of the subtotal, and total holding both added together, rounded to 2 decimal places.
Name it exactly: subtotal, tax, total
3 visible + 0 hidden
loading editor…
Mark this lesson complete
Signed in, your progress follows you to every device.