A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.
Python artificial-intelligencedagdata-sciencedata-visualizationdataflowdeveloper-toolsmachine-learningnotebookspipelinepythonreactivesqlweb-app
fix: auto right-align numeric columns and normalize decimal formatting in tables (#8887)
Kiran Gadhave6bb4852dde81
diff --git a/frontend/src/components/data-table/__tests__/columns.test.tsx b/frontend/src/components/data-table/__tests__/columns.test.tsxindex 06cdea38cf..a0ba8c8daa 100644--- a/frontend/src/components/data-table/__tests__/columns.test.tsx+++ b/frontend/src/components/data-table/__tests__/columns.test.tsx@@ -222,6 +222,75 @@ describe("generateColumns", () => {expect(columns[1].meta?.dataType).toBe("number");});+ it("should auto right-align numeric columns", () => {+ const columns = generateColumns({+ rowHeaders: [],+ selection: null,+ fieldTypes,+ });++ // "age" is a number column — should auto right-align+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ const cell = (columns[1].cell as any)({+ column: {+ columnDef: columns[1],+ },+ renderValue: () => 25,+ getValue: () => 25,+ });+ expect(cell?.props.className).toContain("text-right");++ // "name" is a string column — should remain left-aligned+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ const nameCell = (columns[0].cell as any)({+ column: {+ columnDef: columns[0],+ },+ renderValue: () => "John",+ getValue: () => "John",+ });+ expect(nameCell?.props.className).not.toContain("text-right");+ });++ it("should respect explicit textJustifyColumns over auto alignment", () => {+ const columns = generateColumns({+ rowHeaders: [],+ selection: null,+ fieldTypes,+ textJustifyColumns: { age: "left" },+ });++ // "age" is numeric but explicitly set to left+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ const cell = (columns[1].cell as any)({+ column: {+ columnDef: columns[1],+ },+ renderValue: () => 25,+ getValue: () => 25,+ });+ expect(cell?.props.className).not.toContain("text-right");+ });++ it("should set minFractionDigits from fractionDigitsByColumn", () => {+ const numericFieldTypes: FieldTypesWithExternalType = [+ ["price", ["number", "float64"]],+ ["count", ["integer", "int64"]],+ ];++ const columns = generateColumns({+ rowHeaders: [],+ selection: null,+ fieldTypes: numericFieldTypes,+ fractionDigitsByColumn: { price: 2 },+ });++ // price has 2 fraction digits+ expect(columns[0].meta?.minFractionDigits).toBe(2);+ // count not in fractionDigitsByColumn+ expect(columns[1].meta?.minFractionDigits).toBeUndefined();+ });+it("should handle text justification and wrapping", () => {const columns = generateColumns({rowHeaders: [],@@ -572,6 +641,75 @@ describe("LocaleNumber", () => {);expect(container.textContent).toMatchInlineSnapshot(`"10,000,000,000"`);});++ it("should pad decimals with minFractionDigits", () => {+ const { container } = render(+ <I18nProvider locale="en-US">+ <LocaleNumber value={42} minFractionDigits={2} />+ </I18nProvider>,+ );+ expect(container.textContent).toMatchInlineSnapshot(`"42.00"`);+ });++ it("should pad to minFractionDigits for numbers with fewer decimals", () => {+ const { container } = render(+ <I18nProvider locale="en-US">+ <LocaleNumber value={1234.5} minFractionDigits={3} />+ </I18nProvider>,+ );+ expect(container.textContent).toMatchInlineSnapshot(`"1,234.500"`);+ });++ it("should not truncate decimals beyond minFractionDigits", () => {+ const { container } = render(+ <I18nProvider locale="en-US">+ <LocaleNumber value={1.234_56} minFractionDigits={2} />+ </I18nProvider>,+ );+ expect(container.textContent).toMatchInlineSnapshot(`"1.23456"`);+ });+});++describe("renderCellValue with boolean values", () => {+ const createMockColumn = () =>+ ({+ id: "active",+ columnDef: {+ meta: {+ dataType: "boolean" as const,+ dtype: "bool",+ },+ },+ getColumnFormatting: () => undefined,+ getColumnWrapping: () => undefined,+ applyColumnFormatting: (value: unknown) => value,+ }) as unknown as Column<unknown>;++ it("should render true as True", () => {+ const mockColumn = createMockColumn();+ const result = renderCellValue({+ column: mockColumn,+ renderValue: () => true,+ getValue: () => true,+ selectCell: undefined,+ cellStyles: "",+ });+ const { container } = render(result);+ expect(container.textContent).toBe("True");+ });++ it("should render false as False", () => {+ const mockColumn = createMockColumn();+ const result = renderCellValue({+ column: mockColumn,+ renderValue: () => false,+ getValue: () => false,+ selectCell: undefined,+ cellStyles: "",+ });+ const { container } = render(result);+ expect(container.textContent).toBe("False");+ });});describe("renderCellValue with datetime values", () => {diff --git a/frontend/src/components/data-table/columns.tsx b/frontend/src/components/data-table/columns.tsxindex ba70117313..1c3c30c981 100644--- a/frontend/src/components/data-table/columns.tsx+++ b/frontend/src/components/data-table/columns.tsx@@ -112,6 +112,7 @@ export function generateColumns<T>({headerTooltip,showDataTypes,calculateTopKRows,+ fractionDigitsByColumn,}: {rowHeaders: FieldTypesWithExternalType;selection: DataTableSelection;@@ -122,6 +123,7 @@ export function generateColumns<T>({headerTooltip?: Record<string, string>;showDataTypes?: boolean;calculateTopKRows?: CalculateTopKRows;+ fractionDigitsByColumn?: Record<string, number>;}): ColumnDef<T>[] {// Row-headers are typically index columnsconst rowHeadersSet = new Set(rowHeaders.map(([columnName]) => columnName));@@ -138,6 +140,7 @@ export function generateColumns<T>({rowHeader: isRowHeader,dtype: types?.[1],dataType: types?.[0],+ minFractionDigits: fractionDigitsByColumn?.[key],};}@@ -146,9 +149,23 @@ export function generateColumns<T>({filterType: getFilterTypeForFieldType(types[0]),dtype: types[1],dataType: types[0],+ minFractionDigits: fractionDigitsByColumn?.[key],};};+ const getJustify = (key: string): "left" | "center" | "right" | undefined => {+ // Explicit user override takes precedence+ if (textJustifyColumns?.[key]) {+ return textJustifyColumns[key];+ }+ // Auto right-align numeric columns+ const dataType = getMeta(key).dataType;+ if (dataType === "number" || dataType === "integer") {+ return "right";+ }+ return undefined;+ };+const columnKeys: string[] = [...rowHeadersSet,...fieldTypes.map(([columnName]) => columnName),@@ -186,7 +203,7 @@ export function generateColumns<T>({</div>) : null;- const justify = textJustifyColumns?.[key];+ const justify = getJustify(key);const headerWithType = (<div@@ -254,18 +271,21 @@ export function generateColumns<T>({cell.toggleSelected?.();}- const justify = textJustifyColumns?.[key];+ const justify = getJustify(key);const wrapped = wrappedColumns?.includes(key);const isCellSelected = cell?.getIsSelected?.() || false;const canSelectCell =(selection === "single-cell" || selection === "multi-cell") &&!isCellSelected;+ const dataType = column.columnDef.meta?.dataType;+ const isNumeric = dataType === "number" || dataType === "integer";const cellStyles = getCellStyleClass(justify,wrapped,canSelectCell,isCellSelected,+ isNumeric,);const renderedCell = renderCellValue({@@ -430,6 +450,7 @@ function getCellStyleClass(wrapped: boolean | undefined,canSelectCell: boolean,isSelected: boolean,+ isNumeric?: boolean,): string {return cn(canSelectCell && "cursor-pointer",@@ -438,6 +459,7 @@ function getCellStyleClass("w-full","text-left","truncate",+ isNumeric && "tabular-nums",justify === "center" && "text-center",justify === "right" && "text-right",wrapped && `${COLUMN_WRAPPING_STYLES} break-words`,@@ -589,7 +611,18 @@ export function renderCellValue<TData, TValue>({if (typeof value === "number") {return (<div onClick={selectCell} className={cellStyles}>- <LocaleNumber value={value} />+ <LocaleNumber+ value={value}+ minFractionDigits={column.columnDef.meta?.minFractionDigits}+ />+ </div>+ );+ }++ if (typeof value === "boolean") {+ return (+ <div onClick={selectCell} className={cellStyles}>+ {value ? "True" : "False"}</div>);}@@ -635,9 +668,16 @@ export function renderCellValue<TData, TValue>({);}-export const LocaleNumber = ({ value }: { value: number }) => {+export const LocaleNumber = ({+ value,+ minFractionDigits,+}: {+ value: number;+ minFractionDigits?: number;+}) => {const { locale } = useLocale();const format = useNumberFormatter({+ minimumFractionDigits: minFractionDigits,maximumFractionDigits: maxFractionalDigits(locale),});return format.format(value);diff --git a/frontend/src/components/data-table/filters.ts b/frontend/src/components/data-table/filters.tsindex a9fbc00329..3084000c7e 100644--- a/frontend/src/components/data-table/filters.ts+++ b/frontend/src/components/data-table/filters.ts@@ -16,6 +16,7 @@ declare module "@tanstack/react-table" {dtype?: string;dataType?: DataType;filterType?: FilterType;+ minFractionDigits?: number;}}diff --git a/frontend/src/plugins/impl/DataTablePlugin.tsx b/frontend/src/plugins/impl/DataTablePlugin.tsxindex ee67f9359b..2359c82d2a 100644--- a/frontend/src/plugins/impl/DataTablePlugin.tsx+++ b/frontend/src/plugins/impl/DataTablePlugin.tsx@@ -874,10 +874,35 @@ const DataTableComponent = ({return memoizedUnclampedFieldTypes.slice(0, maxColumns);}, [maxColumns, memoizedUnclampedFieldTypes]);+ // Compute max fractional digits per numeric column for consistent formatting.+ const computedFractionDigits = useMemo(() => {+ const result: Record<string, number> = {};+ if (data && data.length > 0) {+ for (const [colName, types] of memoizedClampedFieldTypes) {+ if (types[0] === "number") {+ let maxDecimals = 0;+ for (const row of data) {+ const val = (row as Record<string, unknown>)[colName];+ if (typeof val === "number" && Number.isFinite(val)) {+ const str = String(val);+ const dotIdx = str.indexOf(".");+ if (dotIdx !== -1) {+ maxDecimals = Math.max(maxDecimals, str.length - dotIdx - 1);+ }+ }+ }+ result[colName] = maxDecimals;+ }+ }+ }+ return result;+ }, [data, memoizedClampedFieldTypes]);+const memoizedRowHeaders = useDeepCompareMemoize(rowHeaders);const memoizedTextJustifyColumns = useDeepCompareMemoize(textJustifyColumns);const memoizedWrappedColumns = useDeepCompareMemoize(wrappedColumns);const memoizedChartSpecModel = useDeepCompareMemoize(chartSpecModel);+ const fractionDigitsByColumn = useDeepCompareMemoize(computedFractionDigits);const shownColumns = memoizedClampedFieldTypes.length;// If the field types are not set, we don't show them@@ -898,6 +923,7 @@ const DataTableComponent = ({// Only show data types if they are explicitly setshowDataTypes: showDataTypes,calculateTopKRows: calculate_top_k_rows,+ fractionDigitsByColumn: fractionDigitsByColumn,}),[selection,@@ -909,6 +935,7 @@ const DataTableComponent = ({memoizedWrappedColumns,headerTooltip,calculate_top_k_rows,+ fractionDigitsByColumn,],);