Skip to content

Build your own AI office with Univer Office SDK. Bring editing, calculation, collaboration, and file processing into your product for people and AI agents. Built on an extensible open-source core.

fix(sheets-numfmt): handle scientific notation formats (#7163)

wpxp12345659058cb0575c
diff --git a/packages/sheets-numfmt/src/__tests__/utils.test.ts b/packages/sheets-numfmt/src/__tests__/utils.test.ts
index 2b76eb05b3..550a3a624e 100644
--- a/packages/sheets-numfmt/src/__tests__/utils.test.ts
+++ b/packages/sheets-numfmt/src/__tests__/utils.test.ts
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-import { cellToRange, currencySymbols, DEFAULT_NUMBER_FORMAT, isPatternEqualWithoutDecimal, LocaleType } from '@univerjs/core';
+import { cellToRange, CellValueType, currencySymbols, DEFAULT_NUMBER_FORMAT, DEFAULT_TEXT_FORMAT_EXCEL, isPatternEqualWithoutDecimal, LocaleType } from '@univerjs/core';
import { RemoveNumfmtMutation, SetNumfmtMutation } from '@univerjs/sheets';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { getCurrencyFormat, getCurrencySymbolByLocale, getCurrencySymbolIconByLocale } from '../base/const/currency-symbols';
@@ -23,6 +23,7 @@ import { getDecimalFromPattern, getDecimalString, isPatternHasDecimal, setPatter
import { mergeNumfmtMutations } from '../utils/mutation';
import { getCurrencyFormatOptions, getCurrencyOptions, getDateFormatOptions, getNumberFormatOptions } from '../utils/options';
import { getPatternPreview, getPatternPreviewIgnoreGeneral, getPatternType } from '../utils/pattern';
+import { getScientificNotationFormatFromCell, isAllowedPatternForScientificNotationNumber, isScientificNotationNumericCell } from '../utils/scientific-notation';
describe('test numfmt utils function', () => {
afterEach(() => {
@@ -106,6 +107,28 @@ describe('test numfmt utils function', () => {
expect(getPatternPreview('[invalid', 42)).toEqual({ result: '42' });
});
+ it('scientific notation helpers detect numeric cells and derive display patterns from mantissa decimals', () => {
+ expect(isScientificNotationNumericCell({ v: 1e21, t: CellValueType.NUMBER })).toBe(true);
+ expect(isScientificNotationNumericCell({ v: 1.2345e31, t: CellValueType.NUMBER })).toBe(true);
+ expect(isScientificNotationNumericCell({ v: '1e21', t: CellValueType.STRING })).toBe(false);
+ expect(isScientificNotationNumericCell({ v: 123, t: CellValueType.NUMBER })).toBe(false);
+ expect(isScientificNotationNumericCell(null)).toBe(false);
+
+ expect(getScientificNotationFormatFromCell({ v: 1e21, t: CellValueType.NUMBER })).toBe('0.00E+00');
+ expect(getScientificNotationFormatFromCell({ v: 1.2e21, t: CellValueType.NUMBER })).toBe('0.00E+00');
+ expect(getScientificNotationFormatFromCell({ v: 1.2345e31, t: CellValueType.NUMBER })).toBe('0.0000E+00');
+ expect(getScientificNotationFormatFromCell({ v: -1.2345e-31, t: CellValueType.NUMBER })).toBe('0.0000E+00');
+ });
+
+ it('scientific notation format guard only allows general, text, and scientific patterns', () => {
+ expect(isAllowedPatternForScientificNotationNumber(undefined)).toBe(true);
+ expect(isAllowedPatternForScientificNotationNumber(DEFAULT_NUMBER_FORMAT)).toBe(true);
+ expect(isAllowedPatternForScientificNotationNumber(DEFAULT_TEXT_FORMAT_EXCEL)).toBe(true);
+ expect(isAllowedPatternForScientificNotationNumber('0.00E+00')).toBe(true);
+ expect(isAllowedPatternForScientificNotationNumber('0.00')).toBe(false);
+ expect(isAllowedPatternForScientificNotationNumber('0%')).toBe(false);
+ });
+
it('mergeNumfmtMutations', () => {
const result = mergeNumfmtMutations([
{
diff --git a/packages/sheets-numfmt/src/commands/commands/__tests__/numfmt.command.spec.ts b/packages/sheets-numfmt/src/commands/commands/__tests__/numfmt.command.spec.ts
index 8f4b4aa389..1e7b475573 100644
--- a/packages/sheets-numfmt/src/commands/commands/__tests__/numfmt.command.spec.ts
+++ b/packages/sheets-numfmt/src/commands/commands/__tests__/numfmt.command.spec.ts
@@ -81,6 +81,8 @@ function createWorkbookData(): IWorkbookData {
2: { v: 12, t: CellValueType.NUMBER },
3: { v: 0.375, t: CellValueType.NUMBER },
4: { v: 8, t: CellValueType.NUMBER },
+ 5: { v: 1e21, t: CellValueType.NUMBER },
+ 6: { v: 1.2345e31, t: CellValueType.NUMBER },
},
1: {
0: { v: 1.23, t: CellValueType.NUMBER, s: 'twoDecimals' },
@@ -194,6 +196,104 @@ describe('Sheets numfmt commands', () => {
expect(numfmtService.getValue('test', 'sheet1', 0, 1)).toBeNull();
});
+ it('only allows general, text, and scientific formats for scientific notation numeric values', async () => {
+ await expect(commandService.executeCommand(SetNumfmtCommand.id, {
+ values: [{ row: 0, col: 5, pattern: '0.00' }],
+ })).resolves.toBe(false);
+ expect(numfmtService.getValue('test', 'sheet1', 0, 5)).toBeNull();
+
+ await expect(commandService.executeCommand(SetNumfmtCommand.id, {
+ values: [{ row: 0, col: 5, pattern: '0.00E+00' }],
+ })).resolves.toBe(true);
+ expect(numfmtService.getValue('test', 'sheet1', 0, 5)).toEqual({ pattern: '0.00E+00' });
+
+ await expect(commandService.executeCommand(SetNumfmtCommand.id, {
+ values: [{ row: 0, col: 5, pattern: DEFAULT_TEXT_FORMAT_EXCEL }],
+ })).resolves.toBe(true);
+ expect(numfmtService.getValue('test', 'sheet1', 0, 5)).toEqual({ pattern: DEFAULT_TEXT_FORMAT_EXCEL });
+
+ await expect(commandService.executeCommand(SetNumfmtCommand.id, {
+ values: [{ row: 0, col: 5 }],
+ })).resolves.toBe(true);
+ expect(numfmtService.getValue('test', 'sheet1', 0, 5)).toBeNull();
+ });
+
+ it('adds decimals to general scientific notation numeric values with a scientific format', async () => {
+ selectionService.addSelections([
+ {
+ range: { startRow: 0, startColumn: 5, endRow: 0, endColumn: 5, rangeType: RANGE_TYPE.NORMAL },
+ primary: null,
+ style: null,
+ },
+ ]);
+
+ await expect(commandService.executeCommand(AddDecimalCommand.id)).resolves.toBe(true);
+
+ expect(numfmtService.getValue('test', 'sheet1', 0, 5)).toEqual({ pattern: '0.000E+00' });
+ });
+
+ it('adds decimals based on the current mantissa decimals for general scientific notation numeric values', async () => {
+ selectionService.addSelections([
+ {
+ range: { startRow: 0, startColumn: 6, endRow: 0, endColumn: 6, rangeType: RANGE_TYPE.NORMAL },
+ primary: null,
+ style: null,
+ },
+ ]);
+
+ await expect(commandService.executeCommand(AddDecimalCommand.id)).resolves.toBe(true);
+
+ expect(numfmtService.getValue('test', 'sheet1', 0, 6)).toEqual({ pattern: '0.00000E+00' });
+ });
+
+ it('adds decimals to mixed general numbers without forcing regular numbers into scientific format', async () => {
+ selectionService.addSelections([
+ {
+ range: { startRow: 0, startColumn: 0, endRow: 0, endColumn: 0, rangeType: RANGE_TYPE.NORMAL },
+ primary: null,
+ style: null,
+ },
+ {
+ range: { startRow: 0, startColumn: 6, endRow: 0, endColumn: 6, rangeType: RANGE_TYPE.NORMAL },
+ primary: null,
+ style: null,
+ },
+ ]);
+
+ await expect(commandService.executeCommand(AddDecimalCommand.id)).resolves.toBe(true);
+
+ expect(numfmtService.getValue('test', 'sheet1', 0, 0)).toEqual({ pattern: '0.00000' });
+ expect(numfmtService.getValue('test', 'sheet1', 0, 6)).toEqual({ pattern: '0.00000E+00' });
+ });
+
+ it('subtracts decimals from general scientific notation numeric values with a scientific format', async () => {
+ selectionService.addSelections([
+ {
+ range: { startRow: 0, startColumn: 5, endRow: 0, endColumn: 5, rangeType: RANGE_TYPE.NORMAL },
+ primary: null,
+ style: null,
+ },
+ ]);
+
+ await expect(commandService.executeCommand(SubtractDecimalCommand.id)).resolves.toBe(true);
+
+ expect(numfmtService.getValue('test', 'sheet1', 0, 5)).toEqual({ pattern: '0.0E+00' });
+ });
+
+ it('subtracts decimals based on the current mantissa decimals for general scientific notation numeric values', async () => {
+ selectionService.addSelections([
+ {
+ range: { startRow: 0, startColumn: 6, endRow: 0, endColumn: 6, rangeType: RANGE_TYPE.NORMAL },
+ primary: null,
+ style: null,
+ },
+ ]);
+
+ await expect(commandService.executeCommand(SubtractDecimalCommand.id)).resolves.toBe(true);
+
+ expect(numfmtService.getValue('test', 'sheet1', 0, 6)).toEqual({ pattern: '0.000E+00' });
+ });
+
it('adds and subtracts decimals based on selections and existing formats', async () => {
selectionService.addSelections([
{
diff --git a/packages/sheets-numfmt/src/commands/commands/add-decimal.command.ts b/packages/sheets-numfmt/src/commands/commands/add-decimal.command.ts
index 2efb556f88..862c566754 100644
--- a/packages/sheets-numfmt/src/commands/commands/add-decimal.command.ts
+++ b/packages/sheets-numfmt/src/commands/commands/add-decimal.command.ts
@@ -20,6 +20,7 @@ import type { ISetNumfmtCommandParams } from './set-numfmt.command';
import { CellValueType, CommandType, ICommandService, isDefaultFormat, IUniverInstanceService, Range } from '@univerjs/core';
import { getSheetCommandTarget, INumfmtService, SheetsSelectionsService } from '@univerjs/sheets';
import { getDecimalFromPattern, setPatternDecimal } from '../../utils/decimal';
+import { getScientificNotationFormatFromCell, isScientificNotationNumericCell } from '../../utils/scientific-notation';
import { SetNumfmtCommand } from './set-numfmt.command';
export const AddDecimalCommand: ICommand = {
@@ -46,6 +47,10 @@ export const AddDecimalCommand: ICommand = {
const numfmtValue = numfmtService.getValue(unitId, subUnitId, row, col);
if (!numfmtValue) {
const cell = target.worksheet.getCellRaw(row, col);
+ if (isScientificNotationNumericCell(cell)) {
+ maxDecimals = Math.max(maxDecimals, getDecimalFromPattern(getScientificNotationFormatFromCell(cell)));
+ return;
+ }
if (!maxDecimals && cell && cell.t === CellValueType.NUMBER && cell.v) {
const regResult = /\.(\d*)$/.exec(String(cell.v));
if (regResult) {
@@ -70,10 +75,12 @@ export const AddDecimalCommand: ICommand = {
Range.foreach(selection.range, (row, col) => {
const numfmtValue = numfmtService.getValue(unitId, subUnitId, row, col);
if (isDefaultFormat(numfmtValue?.pattern)) {
+ const cell = target.worksheet.getCellRaw(row, col);
+ // General scientific notation numbers switch to scientific format before changing decimals.
values.push({
row,
col,
- pattern: defaultPattern,
+ pattern: isScientificNotationNumericCell(cell) ? setPatternDecimal(getScientificNotationFormatFromCell(cell), decimals) : defaultPattern,
});
} else {
const decimals = getDecimalFromPattern((numfmtValue as INumfmtItemWithCache).pattern);
diff --git a/packages/sheets-numfmt/src/commands/commands/set-numfmt.command.ts b/packages/sheets-numfmt/src/commands/commands/set-numfmt.command.ts
index 906cf7d0a9..aa6d9e47e7 100644
--- a/packages/sheets-numfmt/src/commands/commands/set-numfmt.command.ts
+++ b/packages/sheets-numfmt/src/commands/commands/set-numfmt.command.ts
@@ -43,6 +43,7 @@ import {
SetRangeValuesMutation,
transformCellsToRange,
} from '@univerjs/sheets';
+import { isAllowedPatternForScientificNotationNumber, isScientificNotationNumericCell } from '../../utils/scientific-notation';
export interface ISetNumfmtCommandParams {
unitId?: string;
@@ -67,8 +68,17 @@ export const SetNumfmtCommand: ICommand<ISetNumfmtCommandParams> = {
if (!target) return false;
const { unitId, subUnitId, worksheet } = target;
- const setCells = params.values.filter((value) => !!value.pattern) as ISetCellsNumfmt;
- const removeCells = params.values.filter((value) => !value.pattern);
+ // Because of precision issues with scientific notation values, filter out some format settings for them here.
+ const values = params.values.filter((value) => {
+ const cell = worksheet.getCellRaw(value.row, value.col);
+ return !isScientificNotationNumericCell(cell) || isAllowedPatternForScientificNotationNumber(value.pattern);
+ });
+ const setCells = values.filter((value) => !!value.pattern) as ISetCellsNumfmt;
+ const removeCells = values.filter((value) => !value.pattern);
+ if (!setCells.length && !removeCells.length) {
+ return false;
+ }
+
const setRedos = transformCellsToRange(unitId, subUnitId, setCells);
const removeRedos: IRemoveNumfmtMutationParams = {
unitId,
diff --git a/packages/sheets-numfmt/src/commands/commands/subtract-decimal.command.ts b/packages/sheets-numfmt/src/commands/commands/subtract-decimal.command.ts
index f06c44421b..9d16a32bae 100644
--- a/packages/sheets-numfmt/src/commands/commands/subtract-decimal.command.ts
+++ b/packages/sheets-numfmt/src/commands/commands/subtract-decimal.command.ts
@@ -20,6 +20,7 @@ import type { ISetNumfmtCommandParams } from './set-numfmt.command';
import { CellValueType, CommandType, ICommandService, isDefaultFormat, IUniverInstanceService, Range } from '@univerjs/core';
import { getSheetCommandTarget, INumfmtService, SheetsSelectionsService } from '@univerjs/sheets';
import { getDecimalFromPattern, setPatternDecimal } from '../../utils/decimal';
+import { getScientificNotationFormatFromCell, isScientificNotationNumericCell } from '../../utils/scientific-notation';
import { SetNumfmtCommand } from './set-numfmt.command';
export const SubtractDecimalCommand: ICommand = {
@@ -47,6 +48,10 @@ export const SubtractDecimalCommand: ICommand = {
const numfmtValue = numfmtService.getValue(unitId, subUnitId, row, col);
if (!numfmtValue) {
const cell = target.worksheet.getCellRaw(row, col);
+ if (isScientificNotationNumericCell(cell)) {
+ maxDecimals = Math.max(maxDecimals, getDecimalFromPattern(getScientificNotationFormatFromCell(cell)));
+ return;
+ }
if (!maxDecimals && cell && cell.t === CellValueType.NUMBER && cell.v) {
const regResult = /\.(\d*)$/.exec(String(cell.v));
if (regResult) {
@@ -72,10 +77,12 @@ export const SubtractDecimalCommand: ICommand = {
Range.foreach(selection.range, (row, col) => {
const numfmtValue = numfmtService.getValue(unitId, subUnitId, row, col);
if (isDefaultFormat(numfmtValue?.pattern)) {
+ const cell = target.worksheet.getCellRaw(row, col);
+ // General scientific notation numbers switch to scientific format before changing decimals.
values.push({
row,
col,
- pattern: defaultPattern,
+ pattern: isScientificNotationNumericCell(cell) ? setPatternDecimal(getScientificNotationFormatFromCell(cell), decimals) : defaultPattern,
});
} else {
const decimals = getDecimalFromPattern((numfmtValue as INumfmtItemWithCache).pattern);
diff --git a/packages/sheets-numfmt/src/utils/scientific-notation.ts b/packages/sheets-numfmt/src/utils/scientific-notation.ts
new file mode 100644
index 0000000000..fc304d73f7
--- /dev/null
+++ b/packages/sheets-numfmt/src/utils/scientific-notation.ts
@@ -0,0 +1,40 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { ICellData, Nullable } from '@univerjs/core';
+import { CellValueType, isDefaultFormat, isTextFormat } from '@univerjs/core';
+import { getPatternType } from './pattern';
+
+export const DEFAULT_SCIENTIFIC_NOTATION_FORMAT = '0.00E+00';
+
+export function isScientificNotationNumericCell(cell: Nullable<ICellData>): boolean {
+ return cell?.t === CellValueType.NUMBER && cell.v !== undefined && cell.v !== null && /e/i.test(String(cell.v));
+}
+
+export function getScientificNotationFormatFromCell(cell: Nullable<ICellData>): string {
+ const text = String(cell?.v);
+ const eIndex = text.search(/e/i);
+ const decimalIndex = text.indexOf('.');
+ const decimalLength = eIndex > -1 && decimalIndex > -1 ? eIndex - decimalIndex - 1 : 0;
+
+ return `0.${'0'.repeat(Math.max(2, decimalLength))}E+00`;
+}
+
+// Scientific notation numbers cannot be accurately expanded with JS number precision, so only formats that preserve
+// the notation or raw text are allowed.
+export function isAllowedPatternForScientificNotationNumber(pattern?: string): boolean {
+ return isDefaultFormat(pattern) || isTextFormat(pattern) || getPatternType(pattern) === 'scientific';
+}
diff --git a/packages/sheets/src/controllers/number-cell.controller.ts b/packages/sheets/src/controllers/number-cell.controller.ts
index 74d25d0b90..ab8e95a0c3 100644
--- a/packages/sheets/src/controllers/number-cell.controller.ts
+++ b/packages/sheets/src/controllers/number-cell.controller.ts
@@ -60,6 +60,12 @@ export class NumberCellDisplayController extends Disposable {
cell.v = stripErrorMargin(Number(cell.v));
+ // If the cell format is General and the value is a scientific notation number, prevent it from displaying lowercase e.
+ const text = String(cell.v);
+ if (text.includes('e')) {
+ cell.v = text.toUpperCase();
+ }
+
return next(cell);
}