Skip to content

Commit

Permalink
feat: Use currency formatter if measure is a currency
Browse files Browse the repository at this point in the history
  • Loading branch information
ptbrowne committed Aug 23, 2022
1 parent 05bcc25 commit f0dbe2f
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 1 deletion.
13 changes: 13 additions & 0 deletions app/configurator/components/ui-helpers.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,14 @@ describe("useDimensionFormatters", () => {
isNumerical: true,
isKeyDimension: false,
} as DimensionMetaDataFragment,
{
iri: "iri-currency",
isNumerical: true,
isKeyDimension: false,
isCurrency: true,
currencyExponent: 1,
__typename: "Measure",
} as DimensionMetaDataFragment,
])
);
return { formatters };
Expand All @@ -75,6 +83,11 @@ describe("useDimensionFormatters", () => {
const { formatters } = setup();
expect(formatters["iri-number"]("2.33333")).toEqual("2,33");
});

it("should work with currencies", () => {
const { formatters } = setup();
expect(formatters["iri-currency"]("20002.3333")).toEqual("20'002,3");
});
});

describe("time intervals", () => {
Expand Down
14 changes: 13 additions & 1 deletion app/configurator/components/ui-helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ import { ChartProps } from "../../charts/shared/use-chart-state";
import { Observation } from "../../domain/data";
import {
DimensionMetaDataFragment,
Measure,
TemporalDimension,
TimeUnit,
} from "../../graphql/query-hooks";
Expand Down Expand Up @@ -149,9 +150,16 @@ const namedNodeFormatter = (d: DimensionMetaDataFragment) => {
};
};

const currencyFormatter = (d: Measure, locale: string) => {
const formatLocale = getD3FormatLocale(locale);
// Use the currency exponent from the dimension, with default 2
return formatLocale.format(`,.${d.currencyExponent || 2}f`);
};

export const useDimensionFormatters = (
dimensions: DimensionMetaDataFragment[]
) => {
const locale = useLocale();
const formatNumber = useFormatNumber() as unknown as (
d: number | string
) => string;
Expand All @@ -163,7 +171,11 @@ export const useDimensionFormatters = (
dimensions.map((d) => {
let formatter: (s: any) => string;
if (d.__typename === "Measure") {
formatter = formatNumber;
if (d.isCurrency) {
formatter = currencyFormatter(d, locale);
} else {
formatter = formatNumber;
}
} else if (d.__typename === "TemporalDimension") {
formatter = dateFormatterFromDimension(
d,
Expand Down

0 comments on commit f0dbe2f

Please sign in to comment.