Skip to content

Commit

Permalink
Fix some number formatting issues in tables
Browse files Browse the repository at this point in the history
  • Loading branch information
Polleps authored and joepio committed Jan 10, 2024
1 parent 03acd17 commit 8797baf
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 8 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ function FloatCellDisplay({

const formattedValue = formatNumber(
value as number | undefined,
decimalPlaces ?? 2,
decimalPlaces,
numberFormatting,
);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ export function DecimalPlacesInput({
commit: true,
});

const [__, setDecimalPlaces] = useNumber(
const [decimalPlaces, setDecimalPlaces] = useNumber(
resource,
urls.properties.constraints.decimalPlaces,
{ commit: true },
Expand All @@ -32,8 +32,10 @@ export function DecimalPlacesInput({
const newValue = e.target.value;
const num = Number.parseInt(newValue, 10);

if (num < 0) {
setError('Value must be eighter positive, zero or empty.');
if (num < 0 || num > 20) {
setError('Value must be between 0 and 20.', true);

return;
} else {
setError(undefined);
}
Expand Down Expand Up @@ -63,7 +65,9 @@ export function DecimalPlacesInput({
<InputStyled
id={id}
type='number'
defaultValue={decimalPlaces}
min={0}
max={20}
onBlur={onBlur}
onChange={handleDecimalPointChange}
/>
Expand Down
22 changes: 18 additions & 4 deletions browser/data-browser/src/views/TablePage/helpers/formatNumber.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,26 +2,40 @@ import { urls } from '@tomic/react';

export function formatNumber(
value: number | undefined,
numberOfDecimalPlaces: number,
fractionDigits: number | undefined,
formatting?: string,
): string {
if (value === undefined) {
return '';
}

// Bad data like negative values will cause a crash so we need to make it valid before formatting.
const fixedFractionDigits = fixInvalidFractionDigits(fractionDigits);

if (formatting === urls.instances.numberFormats.percentage) {
const formatter = new Intl.NumberFormat('default', {
style: 'percent',
minimumFractionDigits: numberOfDecimalPlaces,
minimumFractionDigits: fixedFractionDigits,
});

return formatter.format(value);
return formatter.format(value / 100);
}

const formatter = new Intl.NumberFormat('default', {
style: 'decimal',
minimumFractionDigits: numberOfDecimalPlaces,
minimumFractionDigits: fixedFractionDigits,
});

return formatter.format(value);
}

function fixInvalidFractionDigits(
fractionDigits: number | undefined,
): number | undefined {
if (fractionDigits === undefined) {
return undefined;
}

// INTL only supports 0-20 fraction digits
return Math.min(20, Math.max(0, fractionDigits));
}

0 comments on commit 8797baf

Please sign in to comment.