DEV Community

oliver
oliver

Posted on

Building a Gold Price Per Gram Calculator in JavaScript

Financial calculators are a great beginner project. They mix real-world math, user input, and clean UI. In this post, we'll build a small gold price per gram calculator that converts an ounce price into a price per gram for any karat.

Gold is traded per troy ounce, which equals 31.1035 grams. Karat defines purity out of 24, so the formula is simple: divide the ounce price by 31.1035, then multiply by karat divided by 24.

Here is the code:

const TROY_OUNCE_GRAMS = 31.1035;

function goldPricePerGram(pricePerOunce, karat = 24) {
  if (pricePerOunce <= 0 || karat <= 0 || karat > 24) {
    throw new Error("Invalid input");
  }
  const pureGram = pricePerOunce / TROY_OUNCE_GRAMS;
  return +(pureGram * (karat / 24)).toFixed(2);
}

[24, 18, 14, 9].forEach(k =>
  console.log(`${k}K: €${goldPricePerGram(3750, k)}/g`)
);
Enter fullscreen mode Exit fullscreen mode

With gold at €3,750 per ounce, this prints about €120.57 per gram for 24K, €90.42 for 18K, €70.33 for 14K and €45.21 for 9K.

To show prices correctly for users in different countries, you can use Intl.NumberFormat:

const eur = new Intl.NumberFormat("es-ES", {
  style: "currency",
  currency: "EUR",
});

console.log(eur.format(goldPricePerGram(3750, 18))); // 90,42 €
Enter fullscreen mode Exit fullscreen mode

Hardcoded prices go stale fast. While testing, I compared my output against Oro Precio, which shows live per-gram prices in euros for every karat. It's a useful sanity check that your formula and rounding are correct. For production, you'd fetch the spot price from a market data API and cache it to avoid rate limits.

Some ideas to extend this project: add a weight input to calculate the value of a full item, fetch live spot prices with fetch(), or build a simple UI with a karat dropdown.

Small projects like this are a great way to practice input validation, number formatting, and working with real data. What would you add to this calculator?

Top comments (0)