All files / src/pages/flowsheet-page/economics/shared/model economicsFormatters.ts

86.66% Statements 26/30
65.38% Branches 17/26
100% Functions 0/0
100% Lines 23/23

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57        29x 28x 28x 28x     28x             14x 14x     76x   76x     112x       22x                   49x 49x 49x 37x 16x 16x 16x 16x 16x 16x       16x 16x    
export function formatAmount(
  value: string | number | null | undefined,
  { maximumFractionDigits = 4 }: { maximumFractionDigits?: number } = {},
) {
  if (value == null || value === "") return "-";
  const parsed = Number(value);
  Iif (!Number.isFinite(parsed)) return String(value);
  const formatted = new Intl.NumberFormat("en-NZ", {
    maximumFractionDigits,
  }).format(Math.abs(parsed));
  return parsed < 0 ? `(${formatted})` : formatted;
}
 
export function formatUnit(
  unit: string | null | undefined,
  resultCurrency: string,
) {
  Iif (!unit) return "-";
  return unit.replace(/^currency(?=\/|$)/, resultCurrency || "currency");
}
 
const INPUT_DECIMAL_PATTERN = /^([+-]?)(\d*)(\.\d*)?$/;
const CURRENCY_UNIT_PATTERN =
  /(^|\/)(?:currency|NZD|USD|AUD|CAD|EUR|GBP|MNZD|MUSD|MAUD|MCAD|MEUR|MGBP)(?=\/|$)/i;
 
export function stripNumericInputFormatting(value: string) {
  return value.replace(/,/g, "");
}
 
export function unitLooksMonetary(unit: string | null | undefined) {
  return CURRENCY_UNIT_PATTERN.test((unit ?? "").trim());
}
 
export function formatNumericInputValue(
  value: string | number | null | undefined,
  {
    defaultToZero = true,
    useGrouping = false,
  }: { defaultToZero?: boolean; useGrouping?: boolean } = {},
) {
  const rawValue = value == null ? "" : String(value);
  const normalizedValue = stripNumericInputFormatting(rawValue);
  if (!normalizedValue.trim()) return defaultToZero ? "0" : "";
  if (!useGrouping) return normalizedValue;
  const match = normalizedValue.match(INPUT_DECIMAL_PATTERN);
  Iif (!match) return normalizedValue;
  const [, sign, wholePart, fractionPart] = match;
  Iif (!wholePart) return normalizedValue;
  const groupedWhole = groupWholeNumber(wholePart);
  return `${sign}${groupedWhole}${fractionPart ?? ""}`;
}
 
function groupWholeNumber(value: string) {
  const normalized = value.replace(/^0+(?=\d)/, "");
  return normalized.replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}