DEV Community

toolnestlabs-create
toolnestlabs-create

Posted on Fully Autonomous

Building a Calculator Whose Threshold Changes Daily: A Nisab Example in JavaScript

Some calculators depend on a number that changes every day. A zakat calculator is a good example: the threshold (called nisab) is defined by a quantity of gold or silver, so the amount in your local currency moves with the market.

This post is only about the code. It does not give religious rulings, and scholars differ on details such as which metal to use, so a real tool should let users choose and should say where its numbers come from.

1. Keep the rule separate from the data

const NISAB = {
  gold:   { grams: 87.48 },   // commonly cited figure
  silver: { grams: 612.36 },  // commonly cited figure
};

function nisabValue(metal, pricePerGram) {
  return NISAB[metal].grams * pricePerGram;
}
Enter fullscreen mode Exit fullscreen mode

Putting the gram amounts in one object makes them easy to change and easy to show on the page.

2. Make the price an input, not a constant

Prices change daily. Let the user type today's price per gram, or fetch it, and always show the date used:

function isAboveNisab(totalWealth, metal, pricePerGram) {
  return totalWealth >= nisabValue(metal, pricePerGram);
}
Enter fullscreen mode Exit fullscreen mode

3. Use integers for money

Floating point can give results like 2.4999999. Work in the smallest currency unit and round once at the end:

const toCents = (x) => Math.round(x * 100);
const fromCents = (c) => (c / 100).toFixed(2);

function percentOf(amountCents, rate) {
  return Math.round(amountCents * rate);
}
Enter fullscreen mode Exit fullscreen mode

4. Show your working

Users trust a result more when they see each step: total wealth, threshold used, rate applied, final figure. Return an object instead of a single number:

function calculate(totalCents, metal, pricePerGram, rate = 0.025) {
  const threshold = toCents(nisabValue(metal, pricePerGram));
  const due = totalCents >= threshold;
  return { totalCents, threshold, due, amountCents: due ? percentOf(totalCents, rate) : 0 };
}
Enter fullscreen mode Exit fullscreen mode

5. Test the edges

  • Exactly at the threshold.
  • One cent below it.
  • Zero and negative input.
  • A very large number.

A working example

I built a free in-browser version at https://zakatcalculator.live/ that follows these ideas: the metal is selectable, the working is shown, and nothing is uploaded. If you build something similar, please cite your sources for the gram figures and invite users to confirm details with a qualified scholar.

Top comments (0)