Mathematics Book 1 Companion: Arithmetic and NumbersMaths Book 1 · Companion
0 / 0

Workbench / Mathematics Book 1 Companion: Arithmetic and Numbers

B1·07

Decimals and Percentages

Around chapter 7: how decimals connect place value, fractions, money and floating point; three other ways to see them; what the chapter simplifies (decimals that end aren't exact in binary, "round half up" isn't the only rule, average percentage changes); how Python's decimal module rounds by reading digits as text; four debugging drills; and interview questions.

6 topics · ~13 min read
Updated Suggest a correction

Understanding it better

Concept map

  • Place value to the right (tenths, hundredths: chapter 2 continued) → decimals are fractions with powers of ten underneath → column arithmetic again.
  • ×10 shifts digits; decimal places add when multiplying; scale both numbers to divide.
  • Fraction → decimal by long division (chapter 4) → ends exactly when the denominator's primes are 2 and 5 (chapter 5) → otherwise repeats (remainders recur) → repeating decimal → fraction by shifting and subtracting → 0.999… = 1.
  • In base 2, only denominators that are powers of 2 end → floats can't store 0.1 → decimal types and whole paise for money.
  • Percent = hundredths of a stated base → three questions, one equation → changes multiply (don't cancel, compound, reverse by dividing) → percent versus percentage points.
  • Next: ratios and rates (chapter 8), powers and logarithms for compounding (chapter 10), rounding and error (chapter 11), decimals that neither end nor repeat (chapter 12).

Explain it differently

A decimal is a price in paise written in rupees. ₹4.35 is 435 paise; the point just says where the rupees stop. Adding prices is adding paise, multiplying a price by a quantity is multiplying paise, and the decimal point is decoration until the end. That's exactly how software should store money.

A repeating decimal is a long division that went round in a circle. Dividing by 7, there are only six possible non-zero remainders, so after at most six steps you're back at a remainder you've seen, and from there the walk repeats. The period is the length of the circle.

Percent is a fraction with a fixed bottom. "18 %" is 18100, chosen so everyone uses the same size of piece and comparisons are easy. Every percentage puzzle is chapter 6's fractions with a denominator of 100, plus the question "a hundredth of what?".

Gaps and misconceptions

What the chapter oversimplifies

1. "A decimal that ends is exact", which is true on paper and false in a float. The chapter's theorem is about base 10. A float is a base-2 fraction, so a decimal ends in a float only if its denominator is a power of 2:

Python
from fractions import Fraction as F
tenths = [f"0.{d}" for d in range(1, 10)]
print("exact as floats:", [s for s in tenths if F(float(s)) == F(s)])
print("of 0.01 to 0.99:", [f"0.{n:02d}" for n in range(1, 100) if F(float(f"0.{n:02d}")) == F(f"0.{n:02d}")])
Text
exact as floats: ['0.5']
of 0.01 to 0.99: ['0.25', '0.50', '0.75']

Of the 99 two-place amounts from 0.01 to 0.99, only 0.25, 0.50 and 0.75 are stored exactly; every other price in paise, written in rupees, is an approximation. The same theorem explains both: in base 2 a fraction ends exactly when its denominator's only prime is 2.

2. "Round half up", which is one rule among several, and not the one your language uses. The chapter rounds halves up. Languages and libraries differ, and floats blur which numbers are halves at all:

JavaScript
console.log((1.005).toFixed(2), (2.675).toFixed(2), (0.125).toFixed(2), (2.5).toFixed(0));
console.log(Math.round(2.5), Math.round(-2.5), Math.round(-0.5));
Text
1.00 2.67 0.13 3
3 -2 -0

Python's round gives 2 -2 0.12 1.0 for round(2.5), round(-2.5), round(0.125, 2) and round(1.005, 2): exact halves go to the even neighbour, and 1.005 is a float just below 1.005. JavaScript's toFixed rounds the exact half 0.125 up to 0.13, and Math.round rounds halves towards positive infinity, so −2.5 becomes −2 and −0.5 becomes −0. The walkthrough shows a decimal library that lets you name the rule. Drill D2 is the commonest consequence.

3. "Percentage changes multiply", so they can't be averaged by adding. The chapter shows a rise and a fall don't cancel. The same fact means the average of yearly percentage changes isn't the average rate:

Python
price = 100
after = price * 1.5 * 0.5              # +50% one year, -50% the next
avg_of_changes = (50 + -50) / 2
per_year = ((after / price) ** 0.5 - 1) * 100
print(f"after: {after}, average of the changes: {avg_of_changes}%")
print(f"steady rate with the same result: {per_year:.2f}% a year")
Text
after: 75.0, average of the changes: 0.0%
steady rate with the same result: -13.40% a year

+50 % then −50 % "averages" 0 %, but 100 becomes 75. The steady rate with the same effect is about −13.4 % a year: the square root of the total multiplier, minus 1 (a geometric mean; chapter 10's roots). Investment returns, inflation and growth must be averaged this way.

Common misconceptions

Misconception What's actually true Where it's shown
"Short decimals like 0.1 or 0.35 are exact in a computer." Only fractions with power-of-two denominators are; of 0.01 to 0.99, only 0.25, 0.50 and 0.75. What the chapter oversimplifies, point 1
"Rounding 2.5 gives 3 everywhere." Python gives 2 (ties to even); JavaScript's Math.round(-2.5) gives −2; name the rule you want. What the chapter oversimplifies, point 2; code walkthrough
"The average yearly change is the average of the yearly percentages." Changes multiply; use the geometric mean. What the chapter oversimplifies, point 3
"int(price * 100) converts rupees to paise." It truncates a float that's often just below the true value: 19.99 becomes 1998. Drill D2
"parseFloat reads any number a person wrote." It stops at the first character it doesn't expect: "1,234.50" becomes 1. Drill D1
"GST is 18 % of the bill." For a bill that includes GST, it's 18118 of it. Drill D3
"Rounded percentages add up to 100." Rounding each can give 99.99 or 101; allocate the rounding. Drill D4

Theoretical gaps: the ideas behind the chapter

  • Every real number has a decimal, but that's a theorem about limits. 0.3―=13 means the sums 0.3,0.33,0.333,… approach 13, and a decimal with infinitely many digits is that limit. Making "approach" precise is the start of analysis (chapter 12, and beyond this book).
  • The period of 1n is a fact about multiplication modulo n. It's the smallest k with 10k≡1(modn), the order of 10 modulo n, and it always divides the number of remainders coprime to n (Euler's theorem, extending Fermat's). The exercises' P3 checked the prime case.
  • Decimal floating point exists. IEEE 754 (2008 revision) also defines decimal formats, used in some financial hardware and databases; Python's decimal module implements the closely related General Decimal Arithmetic specification. Base 10 doesn't remove rounding; it makes the rounding happen at the same places a person would.

Applying it

Code walkthrough

Python's decimal module stores a number as a sign, a string of decimal digits and an exponent, so Decimal("2.675") really is 2.675. Rounding is then a question about digits as text: keep the first prec digits, and decide from the rest whether to leave them, or add 1 to the last kept digit. Excerpts from Lib/_pydecimal.py in Python 3.13, the pure-Python version of the module (on your computer: python3 -c "import _pydecimal; print(_pydecimal.__file__)"):

Python
    def _round_down(self, prec):
        """Also known as round-towards-0, truncate."""
        if _all_zeros(self._int, prec):
            return 0
        else:
            return -1

    def _round_half_up(self, prec):
        """Rounds 5 up (away from 0)"""
        if self._int[prec] in '56789':
            return 1
        elif _all_zeros(self._int, prec):
            return 0
        else:
            return -1

    def _round_half_even(self, prec):
        """Round 5 to even, rest to nearest."""
        if _exact_half(self._int, prec) and \
                (prec == 0 or self._int[prec-1] in '02468'):
            return -1
        else:
            return self._round_half_up(prec)

with, near the end of the file,

Python
_all_zeros = re.compile('0*$').match
_exact_half = re.compile('50*$').match

self._int is the digit string and prec how many digits to keep. Each rule returns 1 (round away: add one to the kept digits), 0 (the dropped digits were all zeros, nothing was lost) or −1 (truncate, and something was lost). _round_half_up looks only at the first dropped digit: 5 to 9 means up. _round_half_even handles one extra case: if the dropped part is exactly a half (a 5 followed only by zeros, tested with a regular expression) and the last kept digit is even, truncate. Measured:

Python
"""How Python's decimal module rounds: digits as text, and a decision of +1, 0 or -1."""
from decimal import Decimal, ROUND_HALF_UP, ROUND_HALF_EVEN, ROUND_HALF_DOWN, ROUND_DOWN, ROUND_UP

print(Decimal("2.675").as_tuple())
print(Decimal(2.675).as_tuple().digits[:8], "... (the float's digits)")
cent = Decimal("0.01")
modes = [("HALF_UP", ROUND_HALF_UP), ("HALF_EVEN", ROUND_HALF_EVEN), ("HALF_DOWN", ROUND_HALF_DOWN),
         ("DOWN", ROUND_DOWN), ("UP", ROUND_UP)]
print("value      " + " ".join(f"{n:>9}" for n, _ in modes))
for s in ("2.675", "2.665", "-2.675", "2.6751", "2.6700"):
    print(f"{s:<10} " + " ".join(f"{str(Decimal(s).quantize(cent, rounding=m)):>9}" for _, m in modes))
Text
DecimalTuple(sign=0, digits=(2, 6, 7, 5), exponent=-3)
(2, 6, 7, 4, 9, 9, 9, 9) ... (the float's digits)
value        HALF_UP HALF_EVEN HALF_DOWN      DOWN        UP
2.675           2.68      2.68      2.67      2.67      2.68
2.665           2.67      2.66      2.66      2.66      2.67
-2.675         -2.68     -2.68     -2.67     -2.67     -2.68
2.6751          2.68      2.68      2.68      2.67      2.68
2.6700          2.67      2.67      2.67      2.67      2.67

Decimal("2.675") has the digits 2, 6, 7, 5; the float 2.675 has 2, 6, 7, 4, 9, 9, 9, 9, …, which is why round(2.675, 2) gives 2.67 (the chapter's lab). With exact decimal digits the five rules differ exactly where they should: 2.675 is a true half, so half-up and half-even both give 2.68 (7 is odd, so half-even rounds up too), while 2.665 splits them (2.67 against 2.66, because 6 is even). 2.6751 is past the half, so every "nearest" rule goes up. And because the rules look at digits, not at the sign, half-up rounds −2.675 to −2.68: "up" means away from zero here, which is the convention most people mean by "round half up" for money. (The module that Python actually imports, _decimal, is a fast C library, libmpdec, that follows the same specification and gives the same results.)

Read it yourself

Using the code above, explain what _round_half_up returns for keeping 3 digits of 2.6700 and of 2.6749, and why it needs _all_zeros at all, since both truncate to 2.67.

Debugging drills

D1. An import that read ₹1,234.50 as one rupee

A web form imports expenses from a spreadsheet export, where amounts are text with separators. Totals are far too small:

JavaScript
// Amounts arrive as display text from a spreadsheet export.
for (const s of ["999.50", "1,234.50", "12,34,567.89", "₹450", "1.234,50"]) {
  console.log(JSON.stringify(s), "->", parseFloat(s), Number(s));
}
Text
"999.50" -> 999.5 999.5
"1,234.50" -> 1 NaN
"12,34,567.89" -> 12 NaN
"₹450" -> NaN NaN
"1.234,50" -> 1.234 NaN

Explain each line, and write the fix.

D2. Prices that lost a paisa

A checkout converts prices to paise with int(price * 100). Some items are charged a paisa less than their label:

Python
for rupees in (19.99, 4.35, 0.29, 1.15, 10.10):
    print(f"{rupees:>6} rupees -> int(x * 100) = {int(rupees * 100):>5} paise   x * 100 = {rupees * 100!r}")
Text
 19.99 rupees -> int(x * 100) =  1998 paise   x * 100 = 1998.9999999999998
  4.35 rupees -> int(x * 100) =   434 paise   x * 100 = 434.99999999999994
  0.29 rupees -> int(x * 100) =    28 paise   x * 100 = 28.999999999999996
  1.15 rupees -> int(x * 100) =   114 paise   x * 100 = 114.99999999999999
  10.1 rupees -> int(x * 100) =  1010 paise   x * 100 = 1010.0

Explain, and fix.

D3. GST that came out too high

A report extracts GST from bills that already include 18 % GST, using the function gst_buggy below. The tax authority's figures are lower:

Python
def gst_buggy(total):            # totals already include 18% GST
    return round(total * 0.18, 2)

def gst_right(total):
    return round(total - total / 1.18, 2)

for total in (118.0, 1180.0, 14999.0):
    print(f"bill {total:>8}: buggy GST {gst_buggy(total):>8}  right {gst_right(total):>8}  over-reported {gst_buggy(total) - gst_right(total):.2f}")
Text
bill    118.0: buggy GST    21.24  right     18.0  over-reported 3.24
bill   1180.0: buggy GST    212.4  right    180.0  over-reported 32.40
bill  14999.0: buggy GST  2699.82  right  2287.98  over-reported 411.84

Explain, and give the correct rule.

D4. Poll results that add up to 101 %

A poll widget shows percentages rounded for display. Users complain the numbers don't add up:

Python
votes = {"Option A": 1, "Option B": 1, "Option C": 1}
total = sum(votes.values())
shown = {k: round(100 * v / total, 2) for k, v in votes.items()}
print(shown, "sum", round(sum(shown.values()), 2))
votes = {"A": 2, "B": 2, "C": 2, "D": 1}
total = sum(votes.values())
shown = {k: round(100 * v / total) for k, v in votes.items()}
print(shown, "sum", sum(shown.values()))
Text
{'Option A': 33.33, 'Option B': 33.33, 'Option C': 33.33} sum 99.99
{'A': 29, 'B': 29, 'C': 29, 'D': 14} sum 101

Explain, and fix so the displayed numbers always add to 100.

Career-oriented

Interview prep

Mid level

Q1. Why is 0.1 + 0.2 != 0.3 in most languages, and how do you compare such numbers?

How to get there. Which fractions a float can store, and what a comparison should mean.

Q2. Write a function that splits ₹1,000 among 3 people and shows each share as a percentage, so that both the amounts and the percentages add up.

How to get there. Exact shares, then rounding with a remainder rule, twice.

Senior level

Q1. Your company reports "average customer growth" as the mean of monthly growth percentages. Finance says it's overstated. Who's right?

How to get there. Changes multiply.

Q2. A partner sends prices as JSON numbers with two decimals. You see occasional one-paisa mismatches in reconciliation. Design the fix.

How to get there. Where the precision is lost and who owns rounding.

Staff level

Q1. A bank product's interest calculation must match its published examples to the paisa across web, mobile and batch systems written in three languages. How do you make that true and keep it true?

How to get there. One specification, one implementation or shared test vectors, named rounding.

Q2. A public dashboard of health statistics is being designed. What rules on decimals and percentages do you set so it can't mislead?

How to get there. The chapter's percent pitfalls, at the scale of a public audience.