JavaScript Project: Calculate Exact Totals in Minor Units
Quick answer
An integer-minor-unit calculator represents prices as whole smallest units rather than binary floating-point decimal fractions. For a two-decimal currency model, 125 means 1.25 major units.
How it works
Use nonnegative safe integer quantities and prices. Multiply each quantity by its minor-unit price and accumulate using a zero initial value; verify products and totals are safe if input is not already tightly bounded. For the practice contract, at most 20 records with quantities up to 1000 and prices up to 100000 guarantee totals below the safe limit. Empty input returns zero.
const items = [{qty: 3, cents: 125}, {qty: 2, cents: 250}];const total = items.reduce((sum,x)=>sum+x.qty*x.cents,0);console.log(total);Expected output in Node.js:
875Three units cost 375 and two units cost 500; the sum is 875.
const items = [{qty: 0, cents: 999}];console.log(items.reduce((s,x)=>s+x.qty*x.cents,0), [].reduce((s,x)=>s+x.qty*x.cents,0));Expected output in Node.js:
0 0Zero quantity and empty input both contribute zero.
Common mistakes
Do not treat all currencies as two-decimal currencies or use a float rounding trick as a general financial calculation policy. Taxes, discounts and currency-specific rounding need explicit rules outside this exercise.
Practice
Calculate totals for an empty basket, a mixed basket and a basket with zero quantities.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
JavaScript Project: Calculate Exact Totals in Minor Units — Knowledge Check
Apply the taught concept and predict the output.
What should the accumulator represent in this project?
Why must multiplication results be considered when using safe integer inputs?
What additional policy is needed before adding taxes to this exercise?
What is the exact console output in JavaScript Project: Calculate Exact Totals in Minor Units example 1?
const items = [{qty: 3, cents: 125}, {qty: 2, cents: 250}];const total = items.reduce((sum,x)=>sum+x.qty*x.cents,0);console.log(total);What is the exact console output in JavaScript Project: Calculate Exact Totals in Minor Units example 2?
const items = [{qty: 0, cents: 999}];console.log(items.reduce((s,x)=>s+x.qty*x.cents,0), [].reduce((s,x)=>s+x.qty*x.cents,0));