Free

Calculator

A calculator project that is really about floating point, wearing a calculator costume.

  • JavaScript
  • CSS
  • HTML

About this project

A calculator with digits, a decimal point, the four operators, percent, sign toggle, clear and backspace, full keyboard control, and a running expression above the current value.

It is really a project about floating point. Type 0.1 + 0.2 into any browser console and you get 0.30000000000000004 — not a JavaScript bug, but what every language with binary floating point does, because one tenth in binary repeats forever the way one third in decimal does.

A calculator therefore has a problem, and there are two easy ways to get it wrong. Show the raw number and the tool looks broken to everyone who is not a programmer. Round everything with toFixed and you start lying about values the machine had exactly right — and worse, the rounding gets stored, so the next operation continues from the lie. This calculator keeps the two jobs separate, which is the entire lesson, and the README is candid about where the approach gives up.

What you will learn

  • Understand why 0.1 + 0.2 is not 0.3, in any language with binary floating point
  • Separate the value you compute from the value you display, and keep the rounding out of the machine
  • Use integer scaling to get exact results where it is safe, and detect when it is not
  • Build a keypad that is fully keyboard-operable without duplicating the click handlers
  • Evaluate arithmetic without eval(), using a small explicit state machine

Before you start

  • JavaScript basics — variables, functions and events
  • A browser and a text editor. Nothing to install.

New to JavaScript? The free JavaScript course covers everything this project assumes.

Academic integrity notice

These projects are provided for learning, experimentation and reference. Understand the code, modify it for your own requirements, and acknowledge external work according to your institution’s academic policies. Priodemy does not supply work to be submitted as your own.