/** * Read numbers the way investors in Mozambique write them. * * Browser number inputs follow the browser's locale: «25.000» becomes 25 and * «1500,50» may be refused, so a value silently changes or a field seems not to * accept input. Here a comma is the decimal mark; dots and spaces between * groups of three digits are thousands separators. The result keeps the * stored, locale-free format ("1500.50") used by every calculation. * * Returns '' for an empty field and null when the text is not a number. */ export function normalizeDecimalInput(raw: string): string | null { const text = raw.replace(/[\s  ]/g, ''); if (text === '') return ''; const sign = text.startsWith('-') ? '-' : ''; const body = sign ? text.slice(1) : text; if (!/^[\d.,]+$/.test(body)) return null; let canonical: string; if (body.includes(',')) { if (body.split(',').length > 2) return null; const [whole, fraction] = body.split(','); if (whole.includes('.') && !thousands(whole.split('.'))) return null; canonical = (whole.replace(/\./g, '') || '0') + (fraction ? '.' + fraction : ''); } else if (body.includes('.')) { const groups = body.split('.'); canonical = thousands(groups) ? groups.join('') : groups.length === 2 ? body : ''; } else canonical = body; if (!/^\d+(\.\d+)?$/.test(canonical)) return null; return sign + canonical; } /** «25.000» or «1.500.000»: a first group of 1–3 digits (not 0) and groups of three. */ function thousands(groups: string[]): boolean { return ( groups.length > 1 && /^[1-9]\d{0,2}$/.test(groups[0]) && groups.slice(1).every((group) => /^\d{3}$/.test(group)) ); } /** The value as the investor will recognise it: thousands spaced, comma decimal. */ export function presentDecimal(canonical: string): string { const [whole, fraction] = canonical.replace('-', '').split('.'); const spaced = whole.replace(/\B(?=(\d{3})+(?!\d))/g, ' '); return ( (canonical.startsWith('-') ? '-' : '') + spaced + (fraction ? ',' + fraction : '') ); }