Emmanuel Akinfulubi

JavaScriptMath

Area and circumference of a circle in JavaScript

Intermediate · 4 min read

Circles are everywhere in code: pizza sizes, the range around a delivery point on a map, progress rings, wheels in a game. The two numbers you need most are the area (the space inside) and the circumference (the distance around the edge). Both use pi, the number 3.14159… that links a circle's width to its edge.

In this tutorial you will compute both for a circle of radius 3, plus a slice of it. Then you will learn something that trips up many tests: you can't safely compare these results to a decimal you typed in. You need to know arrow functions and ** for powers.

The formulas

For a circle of radius r (the distance from the center to the edge):

  • Area = π × r²
  • Circumference = 2 × π × r

A sector is a slice, like a slice of pizza. A 60 degree slice is 60/360, one sixth, of the whole circle. So its area is a sixth of the circle's area, and its curved edge (the arc) is a sixth of the circumference.

Math.PI is close, not exact

Pi has infinitely many digits. JavaScript stores the closest value it can fit, Math.PI:

JavaScript

console.log(Math.PI); // 3.141592653589793

It is extremely close, but it is not pi itself. So every circle result is already a tiny bit off before you do anything else. That is fine for drawing or measuring. It only matters when you compare results exactly, which we will get to in Step 4.

Here is the exercise. Have a go yourself first if you like, then read on and we will build it together.

73 A circle, and what you are allowed to compare

fair

Give the area and circumference of a circle of radius 3, and a 60 degree sector of it. Then compute the same area with the multiplications in a different order, and show why you cannot assert either result against a decimal you typed out.

Stuck? Three hints, smallest first
  1. 1. Math.PI * r ** 2 and 2 * Math.PI * r, and neither is exact in binary.
  2. 2. Reordering a floating-point multiplication can change the last bit.
  3. 3. Compare a rounded value, or a difference against a tolerance, never the raw double against a decimal literal.

Step 1: area and circumference

Step 1

const area = (r) => Math.PI * r ** 2;
const circumference = (r) => 2 * Math.PI * r;
const r = 3;
console.log(area(r), circumference(r)); // 28.274333882308138 18.84955592153876

** is worked out before *, so Math.PI * r ** 2 is π × 9, as the formula says.

Step 2: round for people

Nobody wants 15 decimal places on a screen. A small helper rounds to three:

Step 2

const round3 = (x) => Math.round(x * 1000) / 1000;
console.log(round3(area(r)), round3(circumference(r))); // 28.274 18.85

Multiplying by 1000, rounding to a whole number and dividing back gives three decimal places. The circumference shows only two, 18.85, because the third place is 0 and JavaScript doesn't print trailing zeros.

Step 3: a 60 degree slice

Step 3

const sectorArea = (r, deg) => (area(r) * deg) / 360;
const arcLength = (r, deg) => (circumference(r) * deg) / 360;
console.log(sectorArea(r, 60));             // 4.71238898038469
console.log(arcLength(r, 60) === Math.PI);  // true

The slice's area is a sixth of 28.27…, about 4.712. Its arc is a sixth of 6π, which is π, and here the result comes out exactly equal to Math.PI.

Step 4: the same area, multiplied in a different order

Now a circle of radius 2.8. In maths, π × 2.8² and π × 2.8 × 2.8 are the same thing. In JavaScript:

Step 4

const wide = 2.8;
const squareFirst = Math.PI * wide ** 2;
const stepwise = Math.PI * wide * wide;
console.log(squareFirst === stepwise); // false
console.log(stepwise - squareFirst);   // 3.552713678800501e-15

They differ by about 0.0000000000000036. Every multiplication rounds its result to the nearest number JavaScript can store. Do the multiplications in a different order, and the roundings land in different places. The change is far too small to see on a screen, but === notices.

This means a test like area(3) === 28.2743338823 fails, and so does any typed decimal shorter than all 17 digits. It also means a harmless rewrite of a formula can make an exact-match test fail.

Step 5: compare with a tolerance

The fix is to ask "are these close enough?" instead of "are these identical?":

Step 5

console.log(Math.abs(stepwise - squareFirst) < 1e-12); // true
console.log(round3(area(r)) === 28.274);               // true

Math.abs gives the size of the difference, ignoring the sign, and 1e-12 is 0.000000000001. Rounding both sides to the places you need works too.

Step 6: 22/7 is not pi

School books often use 22/7 for pi. It is handy for mental arithmetic, but it is not pi:

Step 6

console.log(22 / 7);                      // 3.142857142857143
console.log(Math.abs(22 / 7 - Math.PI));  // 0.0012644892673496777

It is off in the third decimal place, which is hundreds of billions of times bigger than the rounding error in Step 4. Always use Math.PI.

The full solution

The answer panel has area, circumference, round3, sectorArea and arcLength, and prints the radius 3 results raw and rounded, the area from the diameter, the 60 degree sector, the radius 2.8 area computed two ways with their difference, and 22/7 against pi. Press Run to see the output.

The answer

const area = (r) => Math.PI * r ** 2;
const circumference = (r) => 2 * Math.PI * r;
const round3 = (x) => Math.round(x * 1000) / 1000;

const r = 3;
const sectorArea = (r, deg) => (area(r) * deg) / 360;
const arcLength = (r, deg) => (circumference(r) * deg) / 360;

// The same product, associated differently.
const wide = 2.8;
const squareFirst = Math.PI * wide ** 2;
const stepwise = Math.PI * wide * wide;

console.log('area, circumference:', area(r), circumference(r));
console.log('to three places    :', round3(area(r)), round3(circumference(r)));
console.log('from the diameter  :', (Math.PI * 6 ** 2) / 4);
console.log('60 degree sector   :', sectorArea(r, 60), 'arc', arcLength(r, 60));
console.log('r = 2.8, two ways  :', squareFirst, stepwise);
console.log('difference         :', stepwise - squareFirst);
console.log('22 / 7 against PI  :', 22 / 7, Math.abs(22 / 7 - Math.PI));

Output


      
8 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 8 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

8 checks

test('the area is 28.274333882308138 and rounds to 28.274', [area(r), round3(area(r))], [28.274333882308138, 28.274]);
test('the circumference is 18.84955592153876, or 18.85 to two places', [circumference(r), Math.round(circumference(r) * 100) / 100], [18.84955592153876, 18.85]);
test('computing it from the diameter gives the identical double', (Math.PI * 6 ** 2) / 4 === area(r), true);
test('doubling the radius quadruples the area, exactly', area(6) === 4 * area(3), true);
test('a 60 degree sector is a sixth of the area, and its arc is pi', [sectorArea(r, 60), arcLength(r, 60) === Math.PI], [4.71238898038469, true]);
test('reordering the multiplication moves the last bit', [squareFirst === stepwise, stepwise - squareFirst], [false, 3.552713678800501e-15]);
test('so the honest comparison is a tolerance, not equality', Math.abs(stepwise - squareFirst) < 1e-12, true);
test('and 22 / 7 is not pi: it is out by 0.0013', [Math.abs(22 / 7 - Math.PI) < 0.002, 22 / 7 === Math.PI], [true, false]);

Math.PI is the nearest double to pi, so every circle result is approximate before you do anything to it. That is fine; what is not fine is comparing such a result to a decimal you typed. area(3) === 28.2743338823 is false, and so is area(3) === 28.274333882308 — the only literal that passes is the full 17-digit double. Round to the places you actually need, or compare a difference against a tolerance.

Order matters too. Math.PI * 2.8 ** 2 and Math.PI * 2.8 * 2.8 differ by about 3.6e-15, because each multiplication rounds and the roundings land differently. Floating-point multiplication is commutative but not associative, so two algebraically identical formulas can return different doubles — which is why a test suite that pins geometry results to === starts failing when someone harmlessly rewrites a formula. Some relations do survive exactly, like area(6) === 4 * area(3) here, but that is luck rather than a rule to depend on.

Common mistakes

  • Comparing a circle result to a typed decimal with ===. It is almost always false. Round first, or compare with a tolerance.
  • Using the diameter as the radius. The radius is half the diameter. Using the diameter makes the area four times too big.
  • Writing (Math.PI * r) ** 2. The brackets square pi as well. Write Math.PI * r ** 2.

Try it yourself

  1. A 30 cm pizza (that is the diameter) costs 4,500 naira and a 40 cm one costs 7,000. Which gives more pizza per naira?
  2. Write radiusFromArea(a) that returns Math.sqrt(a / Math.PI), and check it on area(3) with a tolerance.
  3. Find the area and arc length of a 90 degree slice of a circle with radius 10.

Keep practising

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.