CodingNic

Build the Currency Converter

Add Formatting and Storage Helpers

Build the Currency Converter 10 min read

Add Formatting and Storage Helpers

Add Formatting and Storage Helpers

Open app.js below the state declarations.

The finished project uses one formatter so values look consistent across the converter, rates table, Favorites, and history. Add it first:

javascript
const fmt = n => Number.isFinite(n)
  ? new Intl.NumberFormat("en-US", {
      maximumFractionDigits: n >= 100 ? 2 : 4
    }).format(n)
  : "—";

Now add the JSON helpers used by Favorites and history:

javascript
const read = (key, fallbackValue = []) => {
  try {
    return JSON.parse(localStorage.getItem(key) || JSON.stringify(fallbackValue));
  } catch {
    return fallbackValue;
  }
};

const write = (key, value) => {
  localStorage.setItem(key, JSON.stringify(value));
};

Why now?

These helpers are small, but they remove repeated parsing and formatting code from later lessons.

Checkpoint

In the console, run fmt(0.853) and confirm it returns a readable number. Then run write("test", { ok: true }) followed by read("test").