October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsSlow PC?RecommendedPC slow today? Run a repair scan before it gets worseResolve common Windows issues and optimize system performance.Scan NowOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk6 min

How to Build a Gold Price per Gram Calculator in JavaScript

Build a JavaScript calculator that converts a troy-ounce gold quote to a purity-adjusted price per gram and optional weight-based metal estimate.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

To calculate a gold price per gram from a troy-ounce quote, divide the quote by 31.1034768, then multiply by the gold’s purity fraction. For an item estimate, multiply that result by its eligible gold-alloy weight in grams. This produces an estimated metal value—not a guaranteed jewelry price or dealer offer.

Use the troy-ounce conversion, not the ordinary ounce

Gold is commonly quoted per troy ounce. The National Institute of Standards and Technology (NIST) gives the conversion as 1 troy ounce = 31.1034768 grams. The 2015 NIST guidance uses this factor in its worked examples. Dividing by 28.3495 grams—the ordinary avoirdupois ounce—would produce the wrong result.

As an Amazon Associate I earn from qualifying purchases.

Define the inputs as a price per troy ounce in a stated currency, a purity fraction from 0 to 1, and, if needed, the eligible gold-alloy weight in grams:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  • 24K reference per gram: price per troy ounce ÷ 31.1034768
  • Selected-purity price per gram: price per troy ounce ÷ 31.1034768 × purity fraction
  • Estimated item metal value: selected-purity price per gram × eligible weight in grams

Convert karat or fineness into a purity fraction

Karat input

For a karat value on a 24-part scale, divide the karat number by 24. NIST’s 2015 guidance gives 18K as 75% gold and 12K as 50% gold. For example, 18K becomes 18 / 24, or 0.75.

Fineness input

If the input is fineness in parts per thousand, divide it by 1,000 before multiplying. Label the input convention clearly; a number such as 750 must not be mistaken for a karat value or a fraction. The meaning of a hallmark can depend on the applicable hallmarking regime, so a calculator should not present its chosen convention as an assay of an individual item.

Keep calculation logic separate from input validation

The calculation can remain a small, testable function. Validate the inputs before calling it, and do not round intermediate values for display purposes.

const TROY_OUNCE_GRAMS = 31.1034768;

function getGoldEstimate({ spotPerTroyOunce, purity, weightGrams }) {
  if (!Number.isFinite(spotPerTroyOunce) || spotPerTroyOunce < 0) {
    throw new RangeError("Price must be a finite, nonnegative number.");
  }
  if (!Number.isFinite(purity) || purity < 0 || purity > 1) {
    throw new RangeError("Purity must be a fraction from 0 to 1.");
  }
  if (weightGrams !== undefined &&
      (!Number.isFinite(weightGrams) || weightGrams < 0)) {
    throw new RangeError("Weight must be finite and nonnegative.");
  }

  const price24kPerGram = spotPerTroyOunce / TROY_OUNCE_GRAMS;
  const selectedPurityPerGram = price24kPerGram * purity;

  return {
    price24kPerGram,
    selectedPurityPerGram,
    estimatedMetalValue: weightGrams === undefined
      ? undefined
      : selectedPurityPerGram * weightGrams
  };
}

This example uses JavaScript numbers for straightforward arithmetic. It does not make binary floating-point exact decimal money arithmetic. The goldprice.dev API documentation returns prices as decimal strings and recommends a decimal type when exact money arithmetic matters. If your application has settlement or accounting requirements, use a suitable decimal arithmetic approach and define its rounding rules explicitly.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Build the form around the assumptions that affect the result

Make the inputs explicit so users can see what the estimate depends on:

  • Reference price: label the currency and unit, such as USD per troy ounce.
  • Source and observation time: identify the price provider and show the quote timestamp; indicate when data is stale or unavailable.
  • Purity: say whether the input is karat on a 24-part scale or fineness in parts per thousand.
  • Weight: request grams and explain whether the number should represent gold alloy only.

A jewelry item’s entire scale weight may include stones or materials other than gold. Use only the weight eligible for the calculation; otherwise the estimated metal value can be overstated.

Present the selected-purity amount per gram separately from the total estimated metal value. If no weight is entered, show only the per-gram figure. State the source, currency, and observation time alongside the result rather than calling an unlabelled number “live.”

Format currency for the user’s locale

Use Intl.NumberFormat for locale-sensitive currency display, and keep formatting out of the calculation function. MDN documents the currency-style options in its Intl.NumberFormat reference.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
function formatCurrency(value, locale, currency) {
  return new Intl.NumberFormat(locale, {
    style: "currency",
    currency
  }).format(value);
}

const perGramText = formatCurrency(
  estimate.selectedPurityPerGram,
  "en-US",
  "USD"
);

Choose the locale and currency from your product context or user settings, and show the currency clearly. Currency minor-unit conventions differ, so let the selected currency and product requirements guide displayed precision. Format only after the underlying calculation; do not confuse display rounding with the value retained for further calculations.

Handle live prices as timestamped data

A dynamic quote can be delayed, stale, unavailable, or denominated in a currency different from the one the user wants to see. A robust integration should validate the returned data and make its provenance visible. The World Gold Council’s Gold Price Methodology explains that its chart price is supplied by FastMarkets in USD and converted to other currencies using an exchange rate from the same time or as close as possible. That is a useful example of why a converted price can involve more than one observation time.

One provider’s API may return a price per gram already adjusted for purity; another may provide an ounce reference for your code to convert. Treat provider-specific response fields, refresh advice, caching rules, rate limits, and credential requirements as documentation for that provider—not universal standards. For example, the AlyawmGold documentation describes timestamp and stale-data fields and gives a 30-second minimum refresh recommendation for its latest-price endpoint. Follow the current terms of whichever provider you select.

  1. Request data from your server or approved client integration, using the provider’s documented endpoint and authentication method.
  2. Check the HTTP status, parse the response, and validate that the expected price, currency, unit, and timestamp fields are present and usable.
  3. Show the provider and observation time with the result. If the response marks the quote stale, label it stale; do not silently present a cached value as current.
  4. On a network or parsing failure, show an unavailable state or a clearly timestamped cached fallback. Do not replace a failed update with an old quote while leaving a “live” label in place.
  5. Respect the provider’s documented refresh, caching, rate-limit, and key-handling requirements. Do not expose a secret credential in browser code.

For a direct API integration, compare providers on source attribution, quote timestamps and stale behavior, currency and market coverage, whether prices are per ounce or purity-adjusted per gram, operational limits, browser CORS and credential requirements, and error availability. Documentation alone does not establish a feed’s independent accuracy or uptime.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Work through a clearly labeled example

NIST’s 2015 guidance illustrates the conversion with a reference quote of $1,181.93 per troy ounce: dividing by 31.1034768 gives approximately $38 per gram at 24K. This is an old worked example for explaining the arithmetic, not a current market price. Applying the 18K fraction of 0.75 gives approximately $28.50 per gram, before item-specific deductions or retail costs.

In production, take the quote from the selected data source and display its currency and observation time. Do not reuse the example amount as a default that could be mistaken for a current price.

Explain why an estimate is not an offer

The result estimates the metal value represented by the inputs. It does not account for every factor in a jewelry purchase or sale. NIST cautions that buyer and seller offers usually reflect reductions for karat content and other factors. Retail premiums, workmanship or making charges, taxes, fees, and transaction-specific deductions are also outside this simple calculation.

Make the distinction visible in the interface: label the output “estimated metal value,” identify whether it is per gram or a total, and avoid language that promises what a dealer will pay or what a finished item will cost.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Frequently Asked Questions

How much is gold per gram?

Divide a gold price quoted per troy ounce by 31.1034768 for a 24K reference per gram. For a lower purity, multiply by its fraction of 24K. The result depends on the quote’s currency, source, and observation time.

How do I work out how much my gold is worth?

Convert the per-troy-ounce quote to a per-gram 24K reference, multiply by the item’s purity fraction, then multiply by the eligible gold-alloy weight in grams. This estimates metal value; it is not a guaranteed dealer offer or retail price.

How much is 100 grams of gold?

Multiply the selected-purity price per gram by 100, using a timestamped quote in the stated currency. If the 100 grams includes stones or other non-gold materials, use only the eligible gold-alloy weight.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Leave a Reply

Your email address will not be published. Required fields are marked *

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
PC Slower Than It Used to Be?Free scan - under a minute
Crashes, No Sound, or Screen Glitches?Free driver scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.