The quantity object to convert
The metric-normalized quantity object (unchanged when already metric or countable)
toMetricQuantity({ quantity: 0.3, uom: "lb" }) // Returns { quantity: 136.08, uom: "g" }
toMetricQuantity({ quantity: 2, uom: "lb" }) // Returns { quantity: 907.18, uom: "g" }
toMetricQuantity({ quantity: 1, uom: "gal" }) // Returns { quantity: 3.79, uom: "l" }
toMetricQuantity({ quantity: 100, uom: "g" }) // Returns { quantity: 100, uom: "g" }
export function toMetricQuantity(input: QuantityObject): QuantityObject {
const uom = standardizeUom(input.uom);
if (!uom) return input;
if (uom === UOM.LB || uom === UOM.OZ) {
// toBaseQuantity returns milligrams for mass; step up to grams, then normalize (g -> kg).
const grams = toBaseQuantity(input.quantity, uom) / 1000;
return normalizeQuantity({ quantity: roundToHundredths(grams), uom: UOM.G });
}
if (uom === UOM.GAL || uom === UOM.QT || uom === UOM.FLOZ) {
// toBaseQuantity returns millilitres for volume; normalize (ml -> l).
const millilitres = toBaseQuantity(input.quantity, uom);
return normalizeQuantity({ quantity: roundToHundredths(millilitres), uom: UOM.ML });
}
return input;
}
Converts a quantity to its "standard" (metric) form, leaving metric and countable units untouched. Imperial mass (lb, oz) becomes grams (then normalized up to kg via normalizeQuantity); imperial volume (gal, qt, fl oz) becomes millilitres (then normalized up to l). Built on toBaseQuantity for the conversion factors so suppliers can present a single, comparable unit system regardless of how the source lists it.