Simplify a fraction in JavaScript
Intermediate · 4 min read
A fraction like 6/8 can be written more simply as 3/4. Both mean the same amount, but 3/4 is in lowest terms: no whole number above 1 divides both the top and the bottom. Recipe scaling, music time signatures, screen aspect ratios (1920 by 1080 is 16:9) and exact money splits all need this step.
In this tutorial you will write simplify(numerator, denominator), which reduces a fraction and keeps any minus sign on the top. Then you will add 1/10 and 2/10 as fractions, and compare that with 0.1 + 0.2 in ordinary JavaScript numbers. You need to know the gcd function from the earlier exercises and how to return an array.
Words for the two parts
The numerator is the top number of a fraction, and the denominator is the bottom. In 6/8, the numerator is 6 and the denominator is 8.
The idea: divide by the GCD
The GCD (greatest common divisor) is the biggest number that divides both parts. Divide both by it, and nothing bigger than 1 is left that divides them both. For 6/8, the GCD is 2, so 6/8 becomes 3/4.
Here is the exercise. Try it yourself first if you like, then read on and we will build it together.
40 Simplifying a fraction
fairReduce numerator / denominator to lowest terms, keeping any minus sign on the numerator. Then add 1/10 and 2/10 as fractions and compare the result with the same sum in floating point.
Stuck? Three hints, smallest first
- 1. Divide both parts by their GCD.
- 2. Normalise the sign: if the denominator is negative, flip both.
- 3. A zero numerator reduces to
0/1, and a zero denominator is not a fraction at all.
Step 1: divide both parts
const gcd = (a, b) => {
a = Math.abs(a);
b = Math.abs(b);
while (b) [a, b] = [b, a % b];
return a;
};
const simplifyTry = (numerator, denominator) => {
const g = gcd(numerator, denominator);
return [numerator / g, denominator / g];
};
console.log(simplifyTry(6, 8)); // [ 3, 4 ]
console.log(simplifyTry(3, -9)); // [ 1, -3 ]
The fraction comes back as a pair, [numerator, denominator]. 6/8 works. But 3/-9 gives [1, -3], with the minus sign on the bottom. That is the same number as [-1, 3], yet the two arrays look different and won't compare as equal. We need one standard form.
Step 2: keep the sign on top
If the denominator is negative, flip the sign of both parts. A minus on top and a minus on the bottom cancel out, so the value doesn't change:
const sign = -9 < 0 ? -1 : 1;
console.log([(sign * 3) / 3, (sign * -9) / 3]); // [ -1, 3 ]
Now 3/-9 becomes -1/3. And -4/-8 becomes 1/2: both minus signs go, as they should.
Step 3: the zero cases
Two zeros need thought:
- A zero denominator isn't a fraction at all. You can't divide by zero, so return
nullto say "no answer". - A zero numerator is fine: 0/5 is just 0, and its lowest-terms form is 0/1. But watch
simplify(0, 0):gcd(0, 0)is 0, and dividing by it givesNaN.
The answer handles null first, so the second case can't actually reach the division. It still adds || 1 after the GCD as a guard: if the GCD were ever 0, use 1 instead.
console.log(gcd(0, 5), gcd(0, 0) || 1); // 5 1
Step 4: the full simplify
function simplify(numerator, denominator) {
if (denominator === 0) return null;
const g = gcd(numerator, denominator) || 1;
const sign = denominator < 0 ? -1 : 1;
return [(sign * numerator) / g, (sign * denominator) / g];
}
console.log(simplify(6, 8)); // [ 3, 4 ]
console.log(simplify(3, -9)); // [ -1, 3 ]
console.log(simplify(-4, -8)); // [ 1, 2 ]
console.log(simplify(0, 5)); // [ 0, 1 ]
console.log(simplify(5, 0)); // null
console.log(simplify(7, 9)); // [ 7, 9 ]
A fraction already in lowest terms, like 7/9, comes back unchanged, because its GCD is 1.
Returning null for 5/0 is a choice. Ordinary division gives Infinity for 5 / 0, which is arguably worse, because it carries on through later maths with no complaint. null makes the problem visible.
Step 5: add two fractions
To add a/b and c/d, cross-multiply: the result is (a × d + c × b) over (b × d). Then simplify:
const addFractions = (a, b, c, d) => simplify(a * d + c * b, b * d);
console.log(addFractions(1, 10, 2, 10)); // [ 3, 10 ]
console.log(addFractions(3, 4, 5, 6)); // [ 19, 12 ]
1/10 + 2/10 is 30/100 before simplifying, and 3/10 after.
Step 6: compare with decimals
Now the same sum with ordinary numbers:
console.log(0.1 + 0.2); // 0.30000000000000004
JavaScript stores numbers in binary, and tenths can't be written exactly in binary, just like 1/3 can't be written exactly in decimal. Each value is stored slightly off, and the errors show up in the sum. As two whole numbers, 3 and 10, the fraction has no error at all. Libraries that do exact money and measurement maths use some version of this idea.
The full solution
The answer panel builds gcd, simplify and addFractions, then simplifies each example, adds 1/10 and 2/10, and prints 0.1 + 0.2 beside it. The checks underneath confirm every fraction, including the negative and zero cases, and that 3/4 + 5/6 is 19/12. Press Run to see the output.
const gcd = (a, b) => {
a = Math.abs(a);
b = Math.abs(b);
while (b) [a, b] = [b, a % b];
return a;
};
function simplify(numerator, denominator) {
if (denominator === 0) return null; // not a fraction
const g = gcd(numerator, denominator) || 1; // gcd(0, 0) would be 0
const sign = denominator < 0 ? -1 : 1;
return [(sign * numerator) / g, (sign * denominator) / g];
}
// a/b + c/d = (ad + cb) / bd, then reduce.
const addFractions = (a, b, c, d) => simplify(a * d + c * b, b * d);
console.log('6/8 ->', simplify(6, 8));
console.log('3/-9 ->', simplify(3, -9));
console.log('-4/-8 ->', simplify(-4, -8));
console.log('0/5 ->', simplify(0, 5));
console.log('5/0 ->', simplify(5, 0));
console.log('1/10 + 2/10 as a fraction:', addFractions(1, 10, 2, 10));
console.log('the same sum in doubles :', 0.1 + 0.2);
Output
9 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 9 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('6/8 reduces to 3/4', simplify(6, 8), [3, 4]);
test('a negative denominator moves its sign to the top', simplify(3, -9), [-1, 3]);
test('two negatives cancel', simplify(-4, -8), [1, 2]);
test('zero over anything is 0/1', simplify(0, 5), [0, 1]);
test('and anything over zero is not a fraction', simplify(5, 0), null);
test('an already-reduced fraction is returned unchanged', [simplify(7, 9), simplify(7, 7)], [[7, 9], [1, 1]]);
test('1/10 + 2/10 is exactly 3/10 in fractions', addFractions(1, 10, 2, 10), [3, 10]);
test('while the same sum in doubles is not 0.3', 0.1 + 0.2, 0.30000000000000004);
test('3/4 + 5/6 is 19/12, which no decimal can hold exactly', addFractions(3, 4, 5, 6), [19, 12]);
Two integers and a GCD give you exact rational arithmetic, which is the standard escape from the problem exercise 11 opened: 0.1 + 0.2 is not 0.3 because tenths are not representable in binary, but [1, 10] and [2, 10] add to [3, 10] with no error at all. Every money and measurement library that refuses to round is doing some version of this.
Three details. gcd(0, 0) is 0, so the || 1 stops a division by zero on simplify(0, 0). The sign has to be normalised deliberately, or [1, -3] and [-1, 3] both exist and compare unequal despite being the same number. And returning null for a zero denominator is a choice — 5/0 in doubles is Infinity, which is arguably worse, because it flows onward without complaint.
Common mistakes
- Leaving the sign on the bottom.
[1, -3]and[-1, 3]are the same number but don't compare as equal. Move the sign to the top. - Dividing by a GCD of 0.
gcd(0, 0)is 0. Guard it with|| 1, and reject a zero denominator first. - Forgetting to simplify after adding. 1/10 + 2/10 gives 30/100 until you reduce it.
Try it yourself
- Simplify the screen size 1920 by 1080 to its aspect ratio.
- Write
multiplyFractions(a, b, c, d)and test it on 2/3 times 9/4. You should get 3/2. - Write
toMixed(numerator, denominator)that turns 7/3 into the text'2 1/3'.