Skip to content
Tutorials Center
My learning

Topics

Lesson 136 of 156 ยท Projects

Project: Currency, Unit and Grade Converters

Build four converters in JavaScript - units and temperature, live currency rates with an offline fallback, binary/hex number systems and a weighted grade calculator.

Converters are small, useful and surprisingly instructive. Each one turns a value from one form into another, and doing that well takes the same few ideas every time: put the data in a table, convert through a common base so you don't write every pair by hand, validate what the user types, and keep two fields in sync.

In this project you'll build four tools. A unit converter (length, mass, temperature, data) driven by a table, a currency converter that fetches live exchange rates and still works when the network doesn't, a number system converter for binary, octal, decimal and hexadecimal, and a grade calculator that works out a weighted average and tells you what you still need on the final exam.

It uses ideas from Objects, fetch and the Network, Async/Await, Number and Creating and Removing Elements.

The trick behind every converter: a common base

If you support 8 length units and write a function for each pair, that's 56 conversions. But if every unit knows how to convert to one base unit and from it, you need only 16 small definitions and a one-line formula:

JavaScript
function convert(value, from, to) {
  return to.fromBase(from.toBase(value));   // from -> base -> to
}

For lengths the base is the meter, and each unit is just a multiplier: a kilometer is 1000 base units and an inch is 0.0254. Adding a new unit later means adding one line of data, not new code. Temperature isn't a simple multiplier (Fahrenheit has an offset), but the same shape works if each unit supplies two small functions instead of one number.

Step 1: The unit table and the conversion function

Each unit is an object { label, toBase, fromBase }. A helper factor(n) creates the common multiplier case. Temperature units spell their functions out, with Celsius as the base.

Two details matter for correctness:

  • Floating-point noise. 0.1 * 3 is 0.30000000000000004, and chains of multiplications and divisions in a converter pick up the same kind of error. The tidy() function rounds to 10 significant digits with Number(x.toPrecision(10)), which removes the noise but keeps all the useful precision.
  • Decimal vs binary prefixes. In computing, a kilobyte (KB) is 1000 bytes by the SI definition, and a kibibyte (KiB) is 1024 bytes. Both are in the table so the learner can see the difference.
JS Step 1: A table-driven converter

Press Run (or Ctrl + Enter) to see the console output here.

No output.

-40 is the same in Celsius and Fahrenheit, which is a handy sanity check for a temperature formula. The Kelvin line shows the absolute-zero offset: 0 K is -273.15 ยฐC.

Step 2: The unit converter interface

Now give it a face. The interesting UI problem is two linked fields: the user can type in either box, and the other box updates. The code remembers which side was edited last (lastEdited), and when a unit changes it recalculates from that side. That's what makes it feel natural: change "Feet" to "Meters" in the left box and the right box is recomputed from the number you typed.

Other details:

  • <input type="text" inputmode="decimal"> brings up a number pad on phones but, unlike type="number", lets you type - or . without the field returning an empty value mid-typing. The code replaces a comma with a dot so 2,5 works for European keyboards.
  • If the text is empty or isn't a number, the other box is cleared and the input is marked aria-invalid.
  • Results are formatted with toLocaleString() limited to 8 decimal places, so tiny and huge numbers stay readable.
  • A swap button exchanges the two units.
Step 2: Unit converter

Try typing -40 in Celsius and reading Fahrenheit, then switch to Data storage and compare GB with GiB. Type abc to see the validation, and type in the right-hand box to convert backwards.

Step 3: A currency converter with live rates

Currency is different from units because the numbers change daily. The conversion code is the same idea (go through a base currency), but the rates come from the network, which brings new questions:

  1. Where do you get rates? Many free APIs exist. This example uses the public Frankfurter API, which serves European Central Bank reference rates, needs no key and allows browser requests.
  2. What if the request fails, because the user is offline or the service is down? A converter that shows nothing is useless, so the code keeps a small set of sample rates and says clearly that they're only samples.
  3. What if the request hangs? AbortSignal.timeout(5000) cancels it after five seconds.

Rates are stored relative to one base currency (US dollars here). To convert between any two currencies, divide the target's rate by the source's: amount * rates[to] / rates[from]. It works for every pair, including ones the API never lists directly, like Japanese yen to Brazilian real.

The result is formatted with Intl.NumberFormat and style: "currency", which knows that yen has no decimals and that euros are written differently in different languages.

Never do real money arithmetic with these numbers. Exchange rates here are for display and estimates. Real payment systems store money as integer minor units (cents) and use the rate the bank quotes at the time of the transaction.

Step 3: Currency converter with offline fallback

The page calls render() once before the network request, so the user sees a working converter immediately and the live rates swap in when they arrive. That's the same show something now, improve later idea behind good loading states. If you're offline, press Refresh rates after reconnecting.

In your own project, add a cache: save the rates and their date with localStorage and reuse them for an hour. Exchange rates from this kind of API change once a day, so fetching on every visit wastes bandwidth. The editors on this site run in a sandbox without storage, so the example above keeps the rates in memory only.

Step 4: Number system converter

Programmers often need to see the same number in different bases. JavaScript has two built-in tools for it:

  • parseInt(text, radix) reads text in a base from 2 to 36, and
  • number.toString(radix) writes a number in that base.
JavaScript
parseInt("1010", 2);     // 10
parseInt("ff", 16);      // 255
(255).toString(2);       // "11111111"
(255).toString(16);      // "ff"

For a converter you need more care. parseInt("12abc", 10) returns 12 and silently ignores the rest. A learner who typed an invalid digit deserves an error, so each base gets a regular expression that allows only its own digits ([01] for binary, [0-7] for octal, [0-9a-f] for hex). And ordinary numbers lose precision above 253, so the code uses BigInt, which handles numbers of any size exactly. BigInt can read prefixed strings: BigInt("0b101"), BigInt("0o17"), BigInt("0xff").

The four boxes are linked like the unit converter: edit one, and the other three are rewritten. The edited box is left alone, so your typing never gets reformatted under your cursor. Binary output is grouped in fours (1111 1111) for readability, and spaces are ignored on input.

Step 4: Binary, octal, decimal and hex

Try 255 in the decimal box (you get 1111 1111, 377 and FF), then a huge number like 123456789012345678901234567890, which stays exact because of BigInt. Type 2 in the binary box to see the validation message.

Step 5: A weighted grade calculator

The last converter turns scores into a grade. Many courses weight their parts: homework 30%, midterm 30%, final exam 40%. A plain average of the percentages would be wrong, because a 90% on a 40% exam matters more than a 90% on a 10% quiz.

Each row has a name, the points earned, the points possible and the weight. For each row:

TEXT
contribution = (earned / possible) * weight

The current grade is the sum of the contributions divided by the weights entered so far, so rows that haven't happened yet (no score) are skipped. A table of thresholds then turns the percentage into a letter. An array ordered from best to worst, searched with find(), replaces a long if/else chain:

JavaScript
const GRADES = [
  { min: 90, letter: "A" }, { min: 80, letter: "B" }, { min: 70, letter: "C" },
  { min: 60, letter: "D" }, { min: 0, letter: "F" },
];
const letter = GRADES.find((g) => percent >= g.min).letter;

The most useful feature is the "what do I need?" answer. With a target T percent for the whole course, points already banked B (the sum of contributions) and remaining weight R (100 minus the weights with scores), the average you need on the rest is:

TEXT
needed = (T - B) / R * 100

If needed is above 100, the target is out of reach, and if it's below 0, it's already secured. The code handles both messages, and rows are added and removed with buttons. All output is rendered from the rows array, so rows can come and go freely.

Step 5: Weighted grade calculator

The starting numbers show the most common situation: homework and the midterm are done, and the final exam is empty. Raise the target to 95 and the message changes to "out of reach"; lower it to 40 and it says you've already secured it. Type a score in the final row and the "what do I need" line disappears, because nothing remains.

Notice that the input handler updates the data and calls only renderSummary(), not renderRows(). Rebuilding the rows on every keystroke would replace the input you're typing in and lose focus after each character. When a change can't affect a part of the page, leave that part alone.

Where to go from here

  • More categories. Add area, volume, speed and time to the unit table. Adding a category is a data change only.
  • Cache the rates. Store them with a timestamp in localStorage and refetch only when they're older than an hour.
  • Historical rates. The same API can return a time series. Draw it as an SVG sparkline.
  • Fractions and rounding. Show 2.5 feet as 2 ft 6 in. This is a good exercise in Math.floor() and the remainder operator.
  • GPA calculator. Map letters to grade points and weight them by credit hours.
  • Test the logic. convert() and the grade math are pure functions. Write the round-trip checks from Step 1 as real tests.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does the unit converter convert through a common base unit?

    With a base, convert() is to.fromBase(from.toBase(value)) for every pair. 8 units need 8 definitions, not 56 pair-specific formulas.
  2. 2. What problem does Number(x.toPrecision(10)) solve?

    toPrecision(10) rounds to ten significant digits, so tiny binary representation errors disappear while real precision stays.
  3. 3. How do you convert between two currencies when all rates are stored relative to USD?

    Divide out the source rate to get US dollars, then multiply by the target rate. It works for any pair, even ones the API never lists directly.
  4. 4. Why does the currency converter keep sample rates and show a message when it uses them?

    Networks fail. A fallback keeps the page useful, and the message makes sure nobody mistakes sample numbers for real prices.
  5. 5. Why does the number system converter use BigInt and a regular expression for each base, rather than just parseInt()?

    parseInt("12abc", 10) quietly returns 12, which hides user errors, and plain numbers can't hold huge integers exactly. Validating with a pattern and converting with BigInt fixes both.

Summary

  • Convert through a base: each unit supplies toBase and fromBase, and a new unit is a line of data, not new code.
  • Round to a fixed number of significant digits to hide floating-point noise, and format output with toLocaleString() or Intl.NumberFormat.
  • Linked fields remember which side was edited last, and unit changes recalculate from that side. Validate input and mark errors with aria-invalid.
  • Live data needs a timeout, an error path and a clearly labelled fallback so the tool still works offline.
  • parseInt(text, radix) and toString(radix) convert between bases, and BigInt plus a per-base pattern gives exact, validated results.
  • For weighted grades, sum (earned / possible) * weight and use (target - banked) / remaining to answer "what do I still need?".

Next: Project: Password Strength Meter and OTP Input.