money.ts 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. /**
  2. * Money is held to the cent, so every derived amount rounds the same way.
  3. *
  4. * Binary floats cannot represent most decimal amounts exactly, so a bare
  5. * `cost * 1.5` yields values like 44.980000000000004. Left unrounded those
  6. * reach the database and are summed into subtotals, where the error compounds
  7. * into a visible penny discrepancy on the document.
  8. */
  9. export function roundMoney(value: unknown): number {
  10. const parsed = Number(value)
  11. if (!Number.isFinite(parsed)) return 0
  12. // Round on the decimal value, not the binary approximation of it. A plain
  13. // Math.round(v * 100) / 100 bills 2.5 x 19.99 as 49.97, because that product
  14. // is held as 49.974999999999994 and so falls just short of the halfway point
  15. // it should sit exactly on. The same flaw rounds 1.005 down to 1.00.
  16. //
  17. // Twelve significant digits is well past where the noise lives and well
  18. // short of the ~15 a double carries, so this restores the decimal figure
  19. // without inventing precision. Rounding is symmetric about zero, so a credit
  20. // line rounds by the same magnitude as the charge it reverses.
  21. const normalized = Number(parsed.toPrecision(12))
  22. const scaled = Number((normalized * 100).toPrecision(12))
  23. return (scaled < 0 ? -Math.round(-scaled) : Math.round(scaled)) / 100
  24. }
  25. /** Two decimals, rounded the way the formatter behind every printed amount rounds. */
  26. const PRINTED = new Intl.NumberFormat('en-US', {
  27. minimumFractionDigits: 2,
  28. maximumFractionDigits: 2,
  29. useGrouping: false,
  30. })
  31. /**
  32. * A stored amount to two decimals exactly as the documents print it.
  33. *
  34. * roundMoney above decides what a new figure should be. This answers a
  35. * different question: what does the sheet show for a figure that is already
  36. * stored? Totals written before they were held to the cent sit a hair off
  37. * half a cent (0.18 plus 25% was stored as 0.22499999999999998), and the
  38. * formatter prints that as 0.22 where arithmetic says 0.23. Anything that
  39. * passes an invoice on, to a ledger or a payment, has to carry the printed
  40. * figure, because that is the one the customer holds and pays.
  41. */
  42. export function roundAsPrinted(amount: number): number {
  43. return Number(PRINTED.format(amount))
  44. }