import * as d3Format from "d3-format"; /** * Creates a function which produces formatted versions of the provided numerical value. * @param specifier - d3 format specifier (https://github.com/d3/d3-format) */ export function createNumericalFormatter(specifier = ",.2s"){ const formatter = d3Format.format(specifier); return (n) => { // todo: when upgrade to newest d3-format, delete the n==0 check, change the specifier to $,.2~s if (n === 0){ return "0"; } else if (Math.abs(n) < 1) { return n.toString(); } else{ const s = formatter(n); return s.replace("G", "B"); } }; } /** * Creates a function which produces currency formatted versions of the provided numerical value. * @param specifier - d3 format specifier (https://github.com/d3/d3-format) */ export function createCurrencyFormatter(specifier = "$,.2s"){ const formatter = d3Format.format(specifier); return (n) => { // todo: when upgrade to newest d3-format, delete the n==0 check, change the specifier to $,.2~s if (n === 0){ return "$0"; } else if (Math.abs(n) < 1) { return `$${n}`; } else{ const s = formatter(n); if (n < 0) { return '(' + s.replace("G", "B").replace("-", "") + ')'; } else { return s.replace("G", "B"); } } }; } /** * Produces currency formatted versions of the provided numerical value. * @param value - numerical value to format * @param config - toLocaleString config override * @param rounding - A divisor to round the provided value */ export function formatCurrencyRounding(value, config = {}, rounding = 1){ const localStringConfig = { style: "currency", currency: "USD", minimumFractionDigits: 0, maximumFractionDigits: 0 } ; for (const c in config){ if (config.hasOwnProperty(c)){ localStringConfig[c] = config[c]; } } const valueRounded = value / rounding, valueFormatted = valueRounded.toLocaleString("en-US", localStringConfig); return valueFormatted; }