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(formula): js precision problem (#2371)

Dushusird2c9eebc19f2
diff --git a/packages/core/src/common/request-immediate-macro-task.ts b/packages/core/src/common/request-immediate-macro-task.ts
index bcae7d7903..68b45028fa 100644
--- a/packages/core/src/common/request-immediate-macro-task.ts
+++ b/packages/core/src/common/request-immediate-macro-task.ts
@@ -28,5 +28,9 @@ export function requestImmediateMacroTask(callback: (value?: unknown) => void):
return () => {
cancelled = true;
+ // dispose
+ channel.port1.onmessage = null;
+ channel.port1.close();
+ channel.port2.close();
};
}
diff --git a/packages/engine-formula/src/engine/utils/__tests__/math-kit.spec.ts b/packages/engine-formula/src/engine/utils/__tests__/math-kit.spec.ts
index 677adee4be..396f7d57ca 100644
--- a/packages/engine-formula/src/engine/utils/__tests__/math-kit.spec.ts
+++ b/packages/engine-formula/src/engine/utils/__tests__/math-kit.spec.ts
@@ -15,15 +15,214 @@
*/
import { describe, expect, it } from 'vitest';
-import { truncateNumber } from '../math-kit';
+import { ceil, divide, equals, floor, greaterThan, greaterThanOrEquals, lessThan, lessThanOrEquals, minus, mod, multiply, plus, pow, round, sqrt, stripErrorMargin } from '../math-kit';
describe('Test math kit', () => {
- it('Function truncateNumber', () => {
- expect(truncateNumber('1234567890123456')).toBe(1234567890123450);
- expect(truncateNumber('123.4567890123456789')).toBe(123.456789012345);
- expect(truncateNumber('0.1234567890123456789')).toBe(0.123456789012345);
- expect(truncateNumber('1.234567890123456e+20')).toBe(123456789012345000000);
- expect(truncateNumber('123456789012345')).toBe(123456789012345);
- expect(truncateNumber('0.000000000000123456')).toBe(0.000000000000123456);
+ it('Function plus', () => {
+ expect(plus(1, 2)).toBe(3);
+ expect(stripErrorMargin(plus(0.1, 0.2))).toBe(0.3);
+ expect(stripErrorMargin(plus(0.7, 0.1))).toBe(0.8);
+ expect(stripErrorMargin(plus(0.0000000000001, 0.0000000000002))).toBe(0.0000000000003);
+ });
+
+ it('Function minus', () => {
+ expect(minus(2, 1)).toBe(1);
+ expect(stripErrorMargin(minus(0.3, 0.1))).toBe(0.2);
+ expect(stripErrorMargin(minus(0.8, 0.1))).toBe(0.7);
+ expect(stripErrorMargin(minus(0.0000000000003, 0.0000000000002))).toBe(0.0000000000001);
+ });
+
+ it('Function multiply', () => {
+ expect(multiply(2, 3)).toBe(6);
+ expect(stripErrorMargin(multiply(0.1, 0.2))).toBe(0.02);
+ expect(stripErrorMargin(multiply(0.7, 0.1))).toBe(0.07);
+ expect(multiply(0.0000000000001, 0.0000000000002)).toBe(2e-26);
+ expect(stripErrorMargin(multiply(0.6789, 10000))).toBe(6789);
+ });
+
+ it('Function divide', () => {
+ expect(divide(6, 3)).toBe(2);
+ expect(stripErrorMargin(divide(0.02, 0.1))).toBe(0.2);
+ expect(stripErrorMargin(divide(0.07, 0.1))).toBe(0.7);
+ expect(stripErrorMargin(divide(0.3, 0.1))).toBe(3);
+ expect(divide(0.00000000000000002, 0.0000000000001)).toBe(0.0002);
+ });
+
+ it('Function divide with zero', () => {
+ expect(divide(6, 0)).toBe(Infinity);
+ expect(divide(0.02, 0)).toBe(Infinity);
+ expect(divide(0.07, 0)).toBe(Infinity);
+ expect(divide(0.3, 0)).toBe(Infinity);
+ expect(divide(0.00000000000000002, 0)).toBe(Infinity);
+ });
+
+ it('Function divide with negative zero', () => {
+ expect(divide(6, -0)).toBe(-Infinity);
+ expect(divide(0.02, -0)).toBe(-Infinity);
+ expect(divide(0.07, -0)).toBe(-Infinity);
+ expect(divide(0.3, -0)).toBe(-Infinity);
+ expect(divide(0.00000000000000002, -0)).toBe(-Infinity);
+ });
+
+ // test round
+ it('Function round', () => {
+ expect(round(1.23456789, 2)).toBe(1.23);
+ expect(round(1.235, 2)).toBe(1.24);
+ expect(round(1.23456789, 0)).toBe(1);
+ expect(round(1.23456789, 1)).toBe(1.2);
+ expect(round(1.23456789, 3)).toBe(1.235);
+ expect(round(1.23456789, 4)).toBe(1.2346);
+ expect(round(1.23456789, 5)).toBe(1.23457);
+ expect(round(0.6789, 4)).toBe(0.6789);
+ expect(round(0.6789, 3)).toBe(0.679);
+ expect(round(0.6789, 2)).toBe(0.68);
+ expect(round(0.6789, 1)).toBe(0.7);
+ expect(round(0.6789, 0)).toBe(1);
+ expect(round(0.6749, 1)).toBe(0.7);
+ expect(round(0.6749, 2)).toBe(0.67);
+ expect(round(0.9999, 1)).toBe(1.0);
+ expect(round(0.99999, 1)).toBe(1.0);
+ expect(round(-0.9999, 1)).toBe(-1.0);
+ expect(round(9.9999, 0)).toBe(10);
+ });
+ // test floor
+ it('Function floor', () => {
+ expect(floor(1.23456789, 2)).toBe(1.23);
+ expect(floor(1.235, 2)).toBe(1.23);
+ expect(floor(1.23456789, 0)).toBe(1);
+ expect(floor(1.23456789, 1)).toBe(1.2);
+ expect(floor(1.23456789, 3)).toBe(1.234);
+ expect(floor(1.23456789, 4)).toBe(1.2345);
+ expect(floor(1.23456789, 5)).toBe(1.23456);
+ expect(floor(0.6789, 0)).toBe(0);
+ expect(floor(0.6789, 1)).toBe(0.6);
+ expect(floor(0.6789, 2)).toBe(0.67);
+ expect(floor(0.6789, 3)).toBe(0.678);
+ expect(floor(0.6789, 4)).toBe(0.6789);
+ expect(floor(0.6789, 5)).toBe(0.6789);
+ expect(floor(0.9999, 1)).toBe(0.9);
+ expect(floor(0.9999, 2)).toBe(0.99);
+ expect(floor(0.9999, 3)).toBe(0.999);
+ expect(floor(0.9999, 4)).toBe(0.9999);
+ expect(floor(0.9999, 5)).toBe(0.9999);
+ expect(floor(0.9999, 1)).toBe(0.9);
+ expect(floor(0.99999, 1)).toBe(0.9);
+ expect(floor(1.9999, 1)).toBe(1.9);
+ expect(floor(9.9999, 1)).toBe(9.9);
+ expect(floor(0.0001, 1)).toBe(0);
+ expect(floor(-0.9999, 1)).toBe(-1);
+ });
+
+ // test ceil
+ it('Function ceil', () => {
+ expect(ceil(1.23456789, 2)).toBe(1.24);
+ expect(ceil(1.235, 2)).toBe(1.24);
+ expect(ceil(1.23456789, 0)).toBe(2);
+ expect(ceil(1.23456789, 1)).toBe(1.3);
+ expect(ceil(1.23456789, 3)).toBe(1.235);
+ expect(ceil(1.23456789, 4)).toBe(1.2346);
+ expect(ceil(1.23456789, 5)).toBe(1.23457);
+ expect(ceil(0.6789, 4)).toBe(0.6789);
+ expect(ceil(0.6789, 3)).toBe(0.679);
+ expect(ceil(0.6789, 2)).toBe(0.68);
+ expect(ceil(0.6789, 1)).toBe(0.7);
+ expect(ceil(0.6789, 0)).toBe(1);
+ expect(ceil(0.6709, 1)).toBe(0.7);
+ expect(ceil(0.6709, 2)).toBe(0.68);
+ expect(ceil(0.9999, 1)).toBe(1.0);
+ expect(ceil(0.99999, 1)).toBe(1.0);
+ expect(ceil(1.9999, 1)).toBe(2.0);
+ expect(ceil(9.9999, 1)).toBe(10.0);
+ expect(ceil(0.0001, 1)).toBe(0.1);
+ expect(ceil(-0.9999, 1)).toBe(-0.9);
+ });
+
+ // test mod
+ it('Function mod', () => {
+ expect(mod(5, 2)).toBe(1);
+ expect(mod(5, 3)).toBe(2);
+ expect(mod(5, 4)).toBe(1);
+ expect(mod(5, 5)).toBe(0);
+ expect(mod(5, 6)).toBe(5);
+ });
+
+ // test pow
+ it('Function pow', () => {
+ expect(pow(2, 3)).toBe(8);
+ expect(pow(2, 0)).toBe(1);
+ expect(pow(2, 1)).toBe(2);
+ expect(pow(2, 2)).toBe(4);
+ expect(pow(2, -1)).toBe(0.5);
+ expect(pow(2, -2)).toBe(0.25);
+ expect(pow(2, -3)).toBe(0.125);
+ expect(stripErrorMargin(pow(0.2, 3))).toBe(0.008);
+ });
+ // test sqrt
+ it('Function sqrt', () => {
+ expect(sqrt(4)).toBe(2);
+ expect(sqrt(9)).toBe(3);
+ expect(sqrt(16)).toBe(4);
+ expect(sqrt(25)).toBe(5);
+ expect(sqrt(36)).toBe(6);
+ expect(sqrt(49)).toBe(7);
+ expect(sqrt(64)).toBe(8);
+ expect(sqrt(81)).toBe(9);
+ expect(sqrt(100)).toBe(10);
+ expect(sqrt(2)).toBe(1.4142135623730951);
+ });
+ // test equals
+ it('Function equals', () => {
+ expect(equals(1, 1)).toBe(true);
+ expect(equals(1, 2)).toBe(false);
+ expect(equals(1.1, 1.1)).toBe(true);
+ expect(equals(1.1, 1.2)).toBe(false);
+ expect(equals(1.11, 1.11)).toBe(true);
+ expect(equals(1.11, 1.12)).toBe(false);
+ });
+ // test greaterThan
+ it('Function greaterThan', () => {
+ expect(greaterThan(1, 1)).toBe(false);
+ expect(greaterThan(1, 2)).toBe(false);
+ expect(greaterThan(2, 1)).toBe(true);
+ expect(greaterThan(1.1, 1.1)).toBe(false);
+ expect(greaterThan(1.1, 1.2)).toBe(false);
+ expect(greaterThan(1.2, 1.1)).toBe(true);
+ expect(greaterThan(1.11, 1.11)).toBe(false);
+ expect(greaterThan(1.11, 1.12)).toBe(false);
+ expect(greaterThan(1.12, 1.11)).toBe(true);
+ });
+ // test greaterThanOrEquals
+ it('Function greaterThanOrEquals', () => {
+ expect(greaterThanOrEquals(1, 1)).toBe(true);
+ expect(greaterThanOrEquals(1, 2)).toBe(false);
+ expect(greaterThanOrEquals(2, 1)).toBe(true);
+ expect(greaterThanOrEquals(1.1, 1.1)).toBe(true);
+ expect(greaterThanOrEquals(1.1, 1.2)).toBe(false);
+ expect(greaterThanOrEquals(1.2, 1.1)).toBe(true);
+ expect(greaterThanOrEquals(1.11, 1.11)).toBe(true);
+ expect(greaterThanOrEquals(1.11, 1.12)).toBe(false);
+ expect(greaterThanOrEquals(1.12, 1.11)).toBe(true);
+ });
+ // test lessThan
+ it('Function lessThan', () => {
+ expect(lessThan(1, 1)).toBe(false);
+ expect(lessThan(1, 2)).toBe(true);
+ expect(lessThan(2, 1)).toBe(false);
+ expect(lessThan(1.1, 1.1)).toBe(false);
+ expect(lessThan(1.1, 1.2)).toBe(true);
+ expect(lessThan(1.2, 1.1)).toBe(false);
+ expect(lessThan(1.11, 1.11)).toBe(false);
+ expect(lessThan(1.11, 1.12)).toBe(true);
+ });
+ // test lessThanOrEquals
+ it('Function lessThanOrEquals', () => {
+ expect(lessThanOrEquals(1, 1)).toBe(true);
+ expect(lessThanOrEquals(1, 2)).toBe(true);
+ expect(lessThanOrEquals(2, 1)).toBe(false);
+ expect(lessThanOrEquals(1.1, 1.1)).toBe(true);
+ expect(lessThanOrEquals(1.1, 1.2)).toBe(true);
+ expect(lessThanOrEquals(1.2, 1.1)).toBe(false);
+ expect(lessThanOrEquals(1.11, 1.11)).toBe(true);
+ expect(lessThanOrEquals(1.11, 1.12)).toBe(true);
});
});
diff --git a/packages/engine-formula/src/engine/utils/math-kit.ts b/packages/engine-formula/src/engine/utils/math-kit.ts
index b8d5c0c0c8..cad7c9a641 100644
--- a/packages/engine-formula/src/engine/utils/math-kit.ts
+++ b/packages/engine-formula/src/engine/utils/math-kit.ts
@@ -14,82 +14,185 @@
* limitations under the License.
*/
-import Big from 'big.js';
-
/**
- * Packaging basic mathematical calculation methods, adding precision parameters and solving native JavaScript precision problems
- */
+ * Since Excel follows the IEEE 754 specification, it only handles precision issues when displaying cells. For example, =0.1+0.2, the stored value in XML is 0.30000000000000004, and the displayed value is 0.3. The accuracy of the calculation process does not need to be considered. We only focus on the accuracy of the calculation results. Any result is processed within 15 digits.
-/**
- * Native JavaScript: 0.6789 * 10000 = 6788.999999999999
- *
- * @param a
- * @param b
- * @returns
+ Reference https://en.wikipedia.org/wiki/Numeric_precision_in_Microsoft_Excel
*/
+
+export function plus(a: number, b: number): number {
+ return a + b;
+}
+
+export function minus(a: number, b: number): number {
+ return a - b;
+}
+
export function multiply(a: number, b: number): number {
- return Big(a).times(b).toNumber();
+ return a * b;
+}
+
+export function divide(a: number, b: number): number {
+ return a / b;
}
+/**
+ * Rounds a number to a specified number of decimal places.
+ * @param base The number to round.
+ * @param precision The number of decimal places to round to.
+ * @returns The rounded number.
+ */
export function round(base: number, precision: number): number {
const factor = 10 ** Math.floor(precision);
- return Math.round(multiply(base, factor)) / factor;
+ const epsilon = baseEpsilon(base, factor);
+ return Math.round(multiply(base, factor) + epsilon) / factor;
}
+/**
+ * Rounds down a number to a specified number of decimal places.
+ * @param base The number to round down.
+ * @param precision The number of decimal places to round down to.
+ * @returns The floored number.
+ */
export function floor(base: number, precision: number): number {
const factor = 10 ** Math.floor(precision);
- return Math.floor(multiply(base, factor)) / factor;
+ const epsilon = baseEpsilon(base, factor);
+ return Math.floor(multiply(base, factor) + epsilon) / factor;
}
+/**
+ * Rounds up a number to a specified number of decimal places.
+ * @param base The number to round up.
+ * @param precision The number of decimal places to round up to.
+ * @returns The ceiled number.
+ */
export function ceil(base: number, precision: number): number {
const factor = 10 ** Math.floor(precision);
- return Math.ceil(multiply(base, factor)) / factor;
+ const epsilon = baseEpsilon(base, factor);
+ return Math.ceil(multiply(base, factor) - epsilon) / factor;
+}
+
+export function baseEpsilon(base: number, factor: number) {
+ return Number.EPSILON * Math.max(1, Math.abs(multiply(base, factor)));
}
+/**
+ * Returns the remainder of division of two numbers.
+ * @param base The dividend.
+ * @param divisor The divisor.
+ * @returns The remainder.
+ */
export function mod(base: number, divisor: number): number {
- const bigNumber = new Big(base);
- const bigDivisor = new Big(divisor);
+ return base - divisor * Math.floor(base / divisor);
+}
- const quotient = Math.floor(base / divisor);
+/**
+ * Raises a base number to the power of the exponent.
+ *
+ * @param base The base number.
+ * @param exponent The exponent.
+ * @returns The result of base raised to the power of exponent.
+ */
+export function pow(base: number, exponent: number): number {
+ return base ** exponent;
+}
- const result = bigNumber.minus(bigDivisor.times(quotient));
+/**
+ * Calculates the square root of a number.
+ * @param base The number to take the square root of.
+ * @returns The square root of base.
+ */
+export function sqrt(base: number): number {
+ return Math.sqrt(base);
+}
- return result.toNumber();
+/**
+ * Compares two numbers for equality.
+ * @param a The first number.
+ * @param b The second number.
+ * @returns True if numbers are equal, false otherwise.
+ */
+export function equals(a: number, b: number): boolean {
+ return a === b;
}
-export function pow(base: number, exponent: number): number {
- return base ** exponent;
+/**
+ * Checks if the first number is greater than the second number.
+ * @param a The first number.
+ * @param b The second number.
+ * @returns True if a is greater than b, false otherwise.
+ */
+export function greaterThan(a: number, b: number): boolean {
+ return a > b;
+}
+
+/**
+ * Checks if the first number is greater than or equal to the second number.
+ * @param a The first number.
+ * @param b The second number.
+ * @returns True if a is greater than or equal to b, false otherwise.
+ */
+export function greaterThanOrEquals(a: number, b: number): boolean {
+ return a >= b;
+}
+
+/**
+ * Checks if the first number is less than the second number.
+ * @param a The first number.
+ * @param b The second number.
+ * @returns True if a is less than b, false otherwise.
+ */
+export function lessThan(a: number, b: number): boolean {
+ return a < b;
+}
+
+/**
+ * Checks if the first number is less than or equal to the second number.
+ * @param a The first number.
+ * @param b The second number.
+ * @returns True if a is less than or equal to b, false otherwise.
+ */
+export function lessThanOrEquals(a: number, b: number): boolean {
+ return a <= b;
+}
+
+/**
+ * Complete the number to the specified accuracy and solve the accuracy error,
+ *
+ * e.g. strip(0.30000000000000004,15) => 0.3
+ *
+ * Why precision is 15?
+ *
+ * Excel only saves 15 digits
+ *
+ reference: https://stackoverflow.com/questions/1458633/how-to-deal-with-floating-point-number-precision-in-javascript
+ * @param num
+ * @param precision
+ * @returns
+ */
+export function strip(num: number, precision = 15) {
+ return Number.parseFloat(num.toPrecision(precision));
+}
+
+/**
+ * Set an error range for floating-point calculations. If the error is less than Number.EPSILON, we can consider the result reliable.
+ * @param left
+ * @param right
+ * @returns
+ */
+export function withinErrorMargin(left: number, right: number) {
+ return Math.abs(left - right) < Number.EPSILON;
}
/**
- * Excel can display numbers with up to about 15 digits of precision. This includes the sum of the integer part and the decimal part
- * @param input
+ * Tolerance for the results of accuracy issues to tolerate certain errors
+ *
+ * Why 12?
+ This is an empirical choice. Generally, choosing 12 can solve most of the 0001 and 0009 problems. e.g. floor(5,1.23) = 0.0800000000000001
+ * @param num
* @returns
*/
-export function truncateNumber(input: number | string): number {
- const num = new Big(input);
- const numStr = num.toFixed(); // Convert to fixed-point notation
-
- const parts = numStr.split('.');
- let integerPart = parts[0];
- let decimalPart = parts.length > 1 ? parts[1] : '';
-
- // Handle integer part greater than 15 digits
- if (integerPart.length > 15) {
- integerPart = integerPart.slice(0, 15) + '0'.repeat(integerPart.length - 15);
- }
-
- // Handle decimal part for numbers with an integer part of '0' and leading zeros
- if (integerPart === '0') {
- const nonZeroIndex = decimalPart.search(/[1-9]/); // Find the first non-zero digit
- if (nonZeroIndex !== -1 && nonZeroIndex + 15 < decimalPart.length) {
- decimalPart = decimalPart.slice(0, nonZeroIndex + 15);
- }
- } else if (integerPart.length + decimalPart.length > 15) {
- // Adjust decimal part if total length exceeds 15
- decimalPart = decimalPart.slice(0, 15 - integerPart.length);
- }
-
- // Convert back to number, may cause precision loss for very large or small numbers
- return Number.parseFloat(integerPart + (decimalPart ? `.${decimalPart}` : ''));
+export function stripErrorMargin(num: number, precision = 12) {
+ const stripResult = strip(num, precision);
+ return withinErrorMargin(num, stripResult) ? stripResult : strip(num);
}
diff --git a/packages/engine-formula/src/engine/value-object/__tests__/array-value-ceil.spec.ts b/packages/engine-formula/src/engine/value-object/__tests__/array-value-ceil.spec.ts
index e257bfafce..290ec3b3b0 100644
--- a/packages/engine-formula/src/engine/value-object/__tests__/array-value-ceil.spec.ts
+++ b/packages/engine-formula/src/engine/value-object/__tests__/array-value-ceil.spec.ts
@@ -18,6 +18,7 @@ import { describe, expect, it } from 'vitest';
import { ArrayValueObject, transformToValueObject } from '../array-value-object';
import { NumberValueObject } from '../primitive-object';
+import { stripArrayValue } from '../../../functions/__tests__/create-function-test-bed';
describe('arrayValueObject ceil method test', () => {
const originArrayValueObject = ArrayValueObject.create({
@@ -191,7 +192,7 @@ describe('arrayValueObject ceil method test', () => {
column: 0,
});
- expect((originValueObject.ceil(ceilArrayValueObject) as ArrayValueObject).toValue()).toStrictEqual([
+ expect(stripArrayValue((originValueObject.ceil(ceilArrayValueObject) as ArrayValueObject).toValue())).toStrictEqual([
[1, '#VALUE!', 1, 1, 1],
[1, 1, 1, '#VALUE!', 1000],
]);
diff --git a/packages/engine-formula/src/engine/value-object/__tests__/array-value-floor.spec.ts b/packages/engine-formula/src/engine/value-object/__tests__/array-value-floor.spec.ts
index f204b18b41..5d21ef4446 100644
--- a/packages/engine-formula/src/engine/value-object/__tests__/array-value-floor.spec.ts
+++ b/packages/engine-formula/src/engine/value-object/__tests__/array-value-floor.spec.ts
@@ -18,6 +18,7 @@ import { describe, expect, it } from 'vitest';
import { ArrayValueObject, transformToValueObject } from '../array-value-object';
import { NumberValueObject } from '../primitive-object';
+import { stripArrayValue } from '../../../functions/__tests__/create-function-test-bed';
describe('arrayValueObject floor method test', () => {
const originArrayValueObject = ArrayValueObject.create({
@@ -191,7 +192,7 @@ describe('arrayValueObject floor method test', () => {
column: 0,
});
- expect((originValueObject.floor(floorArrayValueObject) as ArrayValueObject).toValue()).toStrictEqual([
+ expect(stripArrayValue((originValueObject.floor(floorArrayValueObject) as ArrayValueObject).toValue())).toStrictEqual([
[1, '#VALUE!', 1, 1, 1],
[1, 1, 1, '#VALUE!', 0],
]);
diff --git a/packages/engine-formula/src/engine/value-object/__tests__/array-value-minus.spec.ts b/packages/engine-formula/src/engine/value-object/__tests__/array-value-minus.spec.ts
index 38852ae57c..1e8a0a2e38 100644
--- a/packages/engine-formula/src/engine/value-object/__tests__/array-value-minus.spec.ts
+++ b/packages/engine-formula/src/engine/value-object/__tests__/array-value-minus.spec.ts
@@ -19,6 +19,7 @@ import { describe, expect, it } from 'vitest';
import { ArrayValueObject, transformToValueObject } from '../array-value-object';
import { NumberValueObject } from '../primitive-object';
import { ErrorType } from '../../../basics/error-type';
+import { stripArrayValue } from '../../../functions/__tests__/create-function-test-bed';
describe('ArrayValueObject minus method test', () => {
describe('Minus', () => {
@@ -38,7 +39,7 @@ describe('ArrayValueObject minus method test', () => {
const valueObject = new NumberValueObject(1);
- expect((arrayValueObject.minus(valueObject) as ArrayValueObject).toValue()).toStrictEqual([
+ expect(stripArrayValue((arrayValueObject.minus(valueObject) as ArrayValueObject).toValue())).toStrictEqual([
[0, ErrorType.VALUE, 0.23, 0, -1, -1],
[-1, 99, 1.34, ErrorType.VALUE, -4, ErrorType.VALUE],
]);
diff --git a/packages/engine-formula/src/engine/value-object/__tests__/array-value-object.spec.ts b/packages/engine-formula/src/engine/value-object/__tests__/array-value-object.spec.ts
index bd97afc0de..d5230ba0ac 100644
--- a/packages/engine-formula/src/engine/value-object/__tests__/array-value-object.spec.ts
+++ b/packages/engine-formula/src/engine/value-object/__tests__/array-value-object.spec.ts
@@ -22,6 +22,7 @@ import { BooleanValueObject, NumberValueObject } from '../primitive-object';
import type { BaseValueObject } from '../base-value-object';
import { ErrorValueObject } from '../base-value-object';
import { ErrorType } from '../../../basics/error-type';
+import { stripErrorMargin } from '../../utils/math-kit';
describe('arrayValueObject test', () => {
const originArrayValueObject = ArrayValueObject.create({
@@ -219,7 +220,7 @@ describe('arrayValueObject test', () => {
column: 0,
});
- expect(originValueObject.sum().getValue()).toStrictEqual(101.57);
+ expect(stripErrorMargin(Number(originValueObject.sum().getValue()))).toStrictEqual(101.57);
});
});
diff --git a/packages/engine-formula/src/engine/value-object/__tests__/array-value-round.spec.ts b/packages/engine-formula/src/engine/value-object/__tests__/array-value-round.spec.ts
index 6e6c82e28f..07544df2dc 100644
--- a/packages/engine-formula/src/engine/value-object/__tests__/array-value-round.spec.ts
+++ b/packages/engine-formula/src/engine/value-object/__tests__/array-value-round.spec.ts
@@ -18,6 +18,7 @@ import { describe, expect, it } from 'vitest';
import { ArrayValueObject, transformToValueObject } from '../array-value-object';
import { NumberValueObject } from '../primitive-object';
+import { stripArrayValue } from '../../../functions/__tests__/create-function-test-bed';
describe('arrayValueObject round method test', () => {
const originArrayValueObject = ArrayValueObject.create({
@@ -191,7 +192,7 @@ describe('arrayValueObject round method test', () => {
column: 0,
});
- expect((originValueObject.round(roundArrayValueObject) as ArrayValueObject).toValue()).toStrictEqual([
+ expect(stripArrayValue((originValueObject.round(roundArrayValueObject) as ArrayValueObject).toValue())).toStrictEqual([
[1, '#VALUE!', 1, 1, 1],
[1, 1, 1, '#VALUE!', 0],
]);
diff --git a/packages/engine-formula/src/engine/value-object/primitive-object.ts b/packages/engine-formula/src/engine/value-object/primitive-object.ts
index 3261dd7bb4..b6a6641968 100644
--- a/packages/engine-formula/src/engine/value-object/primitive-object.ts
+++ b/packages/engine-formula/src/engine/value-object/primitive-object.ts
@@ -14,15 +14,13 @@
* limitations under the License.
*/
-import Big from 'big.js';
-
import { isRealNum } from '@univerjs/core';
import { reverseCompareOperator } from '../../basics/calculate';
import { BooleanValue, ConcatenateType } from '../../basics/common';
import { ERROR_TYPE_SET, ErrorType } from '../../basics/error-type';
import { compareToken, operatorToken } from '../../basics/token';
import { compareWithWildcard, isWildcard } from '../utils/compare';
-import { ceil, floor, mod, pow, round } from '../utils/math-kit';
+import { ceil, divide, equals, floor, greaterThan, greaterThanOrEquals, lessThan, lessThanOrEquals, minus, mod, multiply, plus, pow, round, sqrt } from '../utils/math-kit';
import { FormulaAstLRU } from '../../basics/cache-lru';
import { comparePatternPriority } from '../utils/numfmt-kit';
import { BaseValueObject, ErrorValueObject } from './base-value-object';
@@ -596,7 +594,7 @@ export class NumberValueObject extends BaseValueObject {
return ErrorValueObject.create(ErrorType.NUM);
}
- const result = Big(currentValue).plus(value).toNumber();
+ const result = plus(currentValue, value);
if (!Number.isFinite(result)) {
return ErrorValueObject.create(ErrorType.NUM);
@@ -606,9 +604,7 @@ export class NumberValueObject extends BaseValueObject {
}
if (typeof value === 'boolean') {
return NumberValueObject.create(
- Big(currentValue)
- .plus(value ? 1 : 0)
- .toNumber()
+ plus(currentValue, value ? 1 : 0)
);
}
return this;
@@ -624,7 +620,7 @@ export class NumberValueObject extends BaseValueObject {
return ErrorValueObject.create(ErrorType.NUM);
}
- const result = Big(currentValue).minus(value).toNumber();
+ const result = minus(currentValue, value);
if (!Number.isFinite(result)) {
return ErrorValueObject.create(ErrorType.NUM);
@@ -634,9 +630,7 @@ export class NumberValueObject extends BaseValueObject {
}
if (typeof value === 'boolean') {
return NumberValueObject.create(
- Big(currentValue)
- .minus(value ? 1 : 0)
- .toNumber()
+ minus(currentValue, value ? 1 : 0)
);
}
return this;
@@ -652,7 +646,7 @@ export class NumberValueObject extends BaseValueObject {
return ErrorValueObject.create(ErrorType.NUM);
}
- const result = Big(currentValue).times(value).toNumber();
+ const result = multiply(currentValue, value);
if (!Number.isFinite(result)) {
return ErrorValueObject.create(ErrorType.NUM);
@@ -661,9 +655,7 @@ export class NumberValueObject extends BaseValueObject {
}
if (typeof value === 'boolean') {
return NumberValueObject.create(
- Big(currentValue)
- .times(value ? 1 : 0)
- .toNumber()
+ multiply(currentValue, value ? 1 : 0)
);
}
return this;
@@ -682,7 +674,7 @@ export class NumberValueObject extends BaseValueObject {
return ErrorValueObject.create(ErrorType.NUM);
}
- const result = Big(currentValue).div(value).toNumber();
+ const result = divide(currentValue, value);
if (!Number.isFinite(result)) {
return ErrorValueObject.create(ErrorType.NUM);
@@ -694,7 +686,7 @@ export class NumberValueObject extends BaseValueObject {
if (value === false) {
return ErrorValueObject.create(ErrorType.DIV_BY_ZERO);
}
- return NumberValueObject.create(Big(currentValue).div(1).toNumber());
+ return NumberValueObject.create(divide(currentValue, 1));
}
return this;
}
@@ -738,17 +730,17 @@ export class NumberValueObject extends BaseValueObject {
private _compareFiniteNumber(currentValue: number, value: number, operator: compareToken): boolean {
switch (operator) {
case compareToken.EQUALS:
- return Big(currentValue).eq(value);
+ return equals(currentValue, value);
case compareToken.GREATER_THAN:
- return Big(currentValue).gt(value);
+ return greaterThan(currentValue, value);
case compareToken.GREATER_THAN_OR_EQUAL:
- return Big(currentValue).gte(value);
+ return greaterThanOrEquals(currentValue, value);
case compareToken.LESS_THAN:
- return Big(currentValue).lt(value);
+ return lessThan(currentValue, value);
case compareToken.LESS_THAN_OR_EQUAL:
- return Big(currentValue).lte(value);
+ return lessThanOrEquals(currentValue, value);
case compareToken.NOT_EQUAL:
- return !Big(currentValue).eq(value);
+ return !equals(currentValue, value);
}
}
@@ -803,7 +795,7 @@ export class NumberValueObject extends BaseValueObject {
return ErrorValueObject.create(ErrorType.NUM);
}
- const result = Big(currentValue).sqrt().toNumber();
+ const result = sqrt(currentValue);
if (!Number.isFinite(result)) {
return ErrorValueObject.create(ErrorType.NUM);
diff --git a/packages/engine-formula/src/functions/__tests__/create-function-test-bed.ts b/packages/engine-formula/src/functions/__tests__/create-function-test-bed.ts
index 1bf5e0aedc..c037bd31ac 100644
--- a/packages/engine-formula/src/functions/__tests__/create-function-test-bed.ts
+++ b/packages/engine-formula/src/functions/__tests__/create-function-test-bed.ts
@@ -57,6 +57,7 @@ import { ISuperTableService, SuperTableService } from '../../services/super-tabl
import type { BaseValueObject, ErrorValueObject } from '../../engine/value-object/base-value-object';
import type { BaseReferenceObject, FunctionVariantType } from '../../engine/reference-object/base-reference-object';
import type { ArrayValueObject } from '../../engine/value-object/array-value-object';
+import { stripErrorMargin } from '../../engine/utils/math-kit';
const getTestWorkbookData = (): IWorkbookData => {
return {
@@ -247,3 +248,12 @@ export function getObjectValue(result: FunctionVariantType) {
}
return (result as BaseValueObject).getValue();
}
+
+export function stripArrayValue(array: (string | number | boolean | null)[][]) {
+ return array.map((row) => row.map((cell) => {
+ if (typeof cell === 'number') {
+ return stripErrorMargin(cell);
+ }
+ return cell;
+ }));
+}
diff --git a/packages/engine-formula/src/functions/math/mod/__tests__/index.spec.ts b/packages/engine-formula/src/functions/math/mod/__tests__/index.spec.ts
index db9e596a9b..9f2da2fad4 100644
--- a/packages/engine-formula/src/functions/math/mod/__tests__/index.spec.ts
+++ b/packages/engine-formula/src/functions/math/mod/__tests__/index.spec.ts
@@ -21,6 +21,7 @@ import { Mod } from '../index';
import { NumberValueObject, StringValueObject } from '../../../../engine/value-object/primitive-object';
import { ArrayValueObject, transformToValue, transformToValueObject } from '../../../../engine/value-object/array-value-object';
import { ErrorType } from '../../../../basics/error-type';
+import { stripArrayValue } from '../../../__tests__/create-function-test-bed';
describe('Test mod function', () => {
const textFunction = new Mod(FUNCTION_NAMES_MATH.MOD);
@@ -66,7 +67,7 @@ describe('Test mod function', () => {
column: 0,
});
const result = textFunction.calculate(number, power);
- expect(transformToValue(result.getArrayValue())).toStrictEqual([
+ expect(stripArrayValue(transformToValue(result.getArrayValue()))).toStrictEqual([
[0, ErrorType.VALUE, 0.08, 0, '#DIV/0!', '#DIV/0!'],
['#DIV/0!', 5, 0.32, ErrorType.VALUE, -1, ErrorType.VALUE],
]);
@@ -87,7 +88,7 @@ describe('Test mod function', () => {
});
const power = NumberValueObject.create(2);
const result = textFunction.calculate(number, power);
- expect(transformToValue(result.getArrayValue())).toStrictEqual([
+ expect(stripArrayValue(transformToValue(result.getArrayValue()))).toStrictEqual([
[1, ErrorType.VALUE, 1.23, 1, 0, 0],
[0, 0, 0.34, ErrorType.VALUE, 1, ErrorType.VALUE],
]);
@@ -120,7 +121,7 @@ describe('Test mod function', () => {
column: 0,
});
const result = textFunction.calculate(number, power);
- expect(transformToValue(result.getArrayValue())).toStrictEqual([
+ expect(stripArrayValue(transformToValue(result.getArrayValue()))).toStrictEqual([
[0, ErrorType.VALUE, 0.23, 0, 0, 0],
[0, 0, 0.34, ErrorType.VALUE, 1, ErrorType.VALUE],
[ErrorType.NA, ErrorType.NA, ErrorType.NA, ErrorType.NA, ErrorType.NA, ErrorType.NA],
diff --git a/packages/engine-formula/src/functions/math/power/__tests__/index.spec.ts b/packages/engine-formula/src/functions/math/power/__tests__/index.spec.ts
index 5fe40e968e..0531039515 100644
--- a/packages/engine-formula/src/functions/math/power/__tests__/index.spec.ts
+++ b/packages/engine-formula/src/functions/math/power/__tests__/index.spec.ts
@@ -21,6 +21,7 @@ import { Power } from '../index';
import { NumberValueObject, StringValueObject } from '../../../../engine/value-object/primitive-object';
import { ArrayValueObject, transformToValue, transformToValueObject } from '../../../../engine/value-object/array-value-object';
import { ErrorType } from '../../../../basics/error-type';
+import { stripArrayValue } from '../../../__tests__/create-function-test-bed';
describe('Test power function', () => {
const textFunction = new Power(FUNCTION_NAMES_MATH.POWER);
@@ -75,9 +76,9 @@ describe('Test power function', () => {
});
const power = NumberValueObject.create(2);
const result = textFunction.calculate(number, power);
- expect(transformToValue(result.getArrayValue())).toStrictEqual([
- [1, ErrorType.VALUE, 1.5128999999999999, 1, 0, 0],
- [0, 10000, 5.4755999999999991, ErrorType.VALUE, 9, ErrorType.VALUE],
+ expect(stripArrayValue(transformToValue(result.getArrayValue()))).toStrictEqual([
+ [1, ErrorType.VALUE, 1.5129, 1, 0, 0],
+ [0, 10000, 5.4756, ErrorType.VALUE, 9, ErrorType.VALUE],
]);
});
@@ -108,9 +109,9 @@ describe('Test power function', () => {
column: 0,
});
const result = textFunction.calculate(number, power);
- expect(transformToValue(result.getArrayValue())).toStrictEqual([
+ expect(stripArrayValue(transformToValue(result.getArrayValue()))).toStrictEqual([
[1, ErrorType.VALUE, 1.23, 1, 0, 0],
- [0, 10000, 5.4755999999999991, ErrorType.VALUE, 9, ErrorType.VALUE],
+ [0, 10000, 5.4756, ErrorType.VALUE, 9, ErrorType.VALUE],
[ErrorType.NA, ErrorType.NA, ErrorType.NA, ErrorType.NA, ErrorType.NA, ErrorType.NA],
]);
});
diff --git a/packages/engine-formula/src/functions/math/subtotal/__tests__/index.spec.ts b/packages/engine-formula/src/functions/math/subtotal/__tests__/index.spec.ts
index d254f65987..bdec5030b8 100644
--- a/packages/engine-formula/src/functions/math/subtotal/__tests__/index.spec.ts
+++ b/packages/engine-formula/src/functions/math/subtotal/__tests__/index.spec.ts
@@ -33,6 +33,7 @@ import { Subtotal } from '../index';
import type { BaseValueObject, ErrorValueObject } from '../../../../engine/value-object/base-value-object';
import { ErrorType } from '../../../../basics/error-type';
import type { ArrayValueObject } from '../../../../engine/value-object/array-value-object';
+import { stripErrorMargin } from '../../../../engine/utils/math-kit';
const getTestWorkbookData = (): IWorkbookData => {
return {
@@ -295,7 +296,7 @@ describe('Test subtotal', () => {
});
it('Stdev.s, Var1 is array, var2 is array', async () => {
const result = await calculate('=SUBTOTAL(7,A1:B2,A3:F4)');
- expect(result).toBe(31.27335040502625);
+ expect(result).toBe(31.273350405026253);
});
it('Stdev.p, Var1 is array, var2 is array', async () => {
const result = await calculate('=SUBTOTAL(8,A1:B2,A3:F4)');
@@ -303,7 +304,7 @@ describe('Test subtotal', () => {
});
it('sum, Var1 is array, var2 is array', async () => {
const result = await calculate('=SUBTOTAL(9,A1:B2,A3:F4)');
- expect(result).toBe(111.57);
+ expect(stripErrorMargin(Number(result))).toBe(111.57);
});
it('Var.s, Var1 is array, var2 is array', async () => {
const result = await calculate('=SUBTOTAL(10,A1:B2,A3:F4)');
@@ -311,7 +312,7 @@ describe('Test subtotal', () => {
});
it('Var.p, Var1 is array, var2 is array', async () => {
const result = await calculate('=SUBTOTAL(11,A1:B2,A3:F4)');
- expect(result).toBe(880.220201);
+ expect(stripErrorMargin(Number(result))).toBe(880.220201);
});
});
@@ -345,16 +346,16 @@ describe('Test subtotal', () => {
expect(result).toBeCloseTo(0.16263456, 7);
result = await calculate('=SUBTOTAL(108,A3:F4)');
- expect(result).toBe(0.115);
+ expect(stripErrorMargin(Number(result))).toBe(0.115);
result = await calculate('=SUBTOTAL(109,A3:F4)');
expect(result).toBe(2.23);
result = await calculate('=SUBTOTAL(110,A3:F4)');
- expect(result).toBe(0.02645);
+ expect(stripErrorMargin(Number(result))).toBe(0.02645);
result = await calculate('=SUBTOTAL(111,A3:F4)');
- expect(result).toBe(0.013225);
+ expect(stripErrorMargin(Number(result))).toBe(0.013225);
});
});
});
diff --git a/packages/engine-formula/src/functions/math/sum/__tests__/index.spec.ts b/packages/engine-formula/src/functions/math/sum/__tests__/index.spec.ts
index 912772030e..626ebab894 100644
--- a/packages/engine-formula/src/functions/math/sum/__tests__/index.spec.ts
+++ b/packages/engine-formula/src/functions/math/sum/__tests__/index.spec.ts
@@ -22,6 +22,7 @@ import { BooleanValueObject, NullValueObject, NumberValueObject, StringValueObje
import { ArrayValueObject, transformToValueObject } from '../../../../engine/value-object/array-value-object';
import { ErrorType } from '../../../../basics/error-type';
import { ErrorValueObject } from '../../../../engine/value-object/base-value-object';
+import { stripErrorMargin } from '../../../../engine/utils/math-kit';
describe('Test sum function', () => {
const textFunction = new Sum(FUNCTION_NAMES_MATH.SUM);
@@ -102,7 +103,7 @@ describe('Test sum function', () => {
column: 0,
});
const result = textFunction.calculate(var1, var2);
- expect(result.getValue()).toBe(103.57);
+ expect(stripErrorMargin(Number(result.getValue()))).toBe(103.57);
});
});
});
diff --git a/packages/engine-formula/src/functions/statistical/stdev-p/__tests__/index.spec.ts b/packages/engine-formula/src/functions/statistical/stdev-p/__tests__/index.spec.ts
index 83f6065e7c..ca61c11b32 100644
--- a/packages/engine-formula/src/functions/statistical/stdev-p/__tests__/index.spec.ts
+++ b/packages/engine-formula/src/functions/statistical/stdev-p/__tests__/index.spec.ts
@@ -110,7 +110,7 @@ describe('Test stdev.p function', () => {
column: 0,
});
const result = textFunction.calculate(var1, var2);
- expect(result.getValue()).toBe(34.82321961694231);
+ expect(result.getValue()).toBe(34.82321961694232);
});
});
});
diff --git a/packages/engine-formula/src/index.ts b/packages/engine-formula/src/index.ts
index 70dabcae1b..6c5cdba438 100644
--- a/packages/engine-formula/src/index.ts
+++ b/packages/engine-formula/src/index.ts
@@ -151,3 +151,4 @@ export { IActiveDirtyManagerService } from './services/active-dirty-manager.serv
export type { IRangeChange } from './models/formula-data.model';
export { handleNumfmtInCell } from './engine/utils/numfmt-kit';
export { AsyncArrayObject } from './engine/reference-object/base-reference-object';
+export { strip, stripErrorMargin } from './engine/utils/math-kit';
diff --git a/packages/engine-formula/src/services/calculate-formula.service.ts b/packages/engine-formula/src/services/calculate-formula.service.ts
index 7754ef85f0..f48ea386b2 100644
--- a/packages/engine-formula/src/services/calculate-formula.service.ts
+++ b/packages/engine-formula/src/services/calculate-formula.service.ts
@@ -241,12 +241,15 @@ export class CalculateFormulaService extends Disposable {
this._executionInProgressListener$.next(this._runtimeService.getRuntimeState());
+ let pendingTasks: (() => void)[] = [];
+
for (let i = 0, len = treeList.length; i < len; i++) {
/**
* For every functions, execute a setTimeout to wait for external command input.
*/
await new Promise((resolve) => {
- requestImmediateMacroTask(resolve);
+ const calcelTask = requestImmediateMacroTask(resolve);
+ pendingTasks.push(calcelTask);
});
if (this._runtimeService.isStopExecution()) {
@@ -314,6 +317,10 @@ export class CalculateFormulaService extends Disposable {
this._executionInProgressListener$.next(this._runtimeService.getRuntimeState());
}
+ // clear all pending tasks
+ pendingTasks.forEach((cancel) => cancel());
+ pendingTasks = [];
+
if (treeList.length > 0) {
this._runtimeService.markedAsSuccessfullyExecuted();
} else if (!isArrayFormulaState) {
diff --git a/packages/sheets-formula/src/controllers/array-formula-display.controller.ts b/packages/sheets-formula/src/controllers/array-formula-display.controller.ts
index 97667c093a..5c7248723a 100644
--- a/packages/sheets-formula/src/controllers/array-formula-display.controller.ts
+++ b/packages/sheets-formula/src/controllers/array-formula-display.controller.ts
@@ -17,7 +17,7 @@
import type { ICommandInfo } from '@univerjs/core';
import { CellValueType, Disposable, ICommandService, LifecycleStages, OnLifecycle, ThemeService } from '@univerjs/core';
import type { ISetArrayFormulaDataMutationParams } from '@univerjs/engine-formula';
-import { FormulaDataModel, SetArrayFormulaDataMutation } from '@univerjs/engine-formula';
+import { FormulaDataModel, SetArrayFormulaDataMutation, stripErrorMargin } from '@univerjs/engine-formula';
import { INTERCEPTOR_POINT, SheetInterceptorService } from '@univerjs/sheets';
import { Inject } from '@wendellhu/redi';
@@ -73,37 +73,6 @@ export class ArrayFormulaDisplayController extends Disposable {
return next(cell);
}
- // const numfmtItemMap = this._formulaDataModel.getNumfmtItemMap();
- // const numfmtItem = numfmtItemMap[unitId]?.[subUnitId]?.[row]?.[col];
-
- // if (numfmtItem) {
- // const value = cellData?.v;
- // const type = cellData?.t;
-
- // if (value == null || type !== CellValueType.NUMBER) {
- // return next(cell);
- // }
-
- // const info = getPatternPreview(numfmtItem, value as number);
-
- // if (info.color) {
- // const colorMap = this._themeService.getCurrentTheme();
- // const color = colorMap[`${info.color}500`];
- // return {
- // ...cell,
- // v: info.result,
- // t: CellValueType.STRING,
- // s: { cl: { rgb: color } },
- // };
- // }
-
- // return {
- // ...cell,
- // v: info.result,
- // t: CellValueType.STRING,
- // };
- // }
-
// The cell in the upper left corner of the array formula also triggers the default value determination
if (cellData.v == null && cellData.t == null) {
return next({ ...cell,
@@ -113,6 +82,15 @@ export class ArrayFormulaDisplayController extends Disposable {
});
}
+ // Dealing with precision issues
+ if (cell?.t === CellValueType.NUMBER && typeof cell?.v === 'number') {
+ return next({
+ ...cell,
+ ...cellData,
+ v: stripErrorMargin(cell.v),
+ });
+ }
+
return next({ ...cell, ...cellData });
},
})
diff --git a/packages/sheets-formula/src/controllers/formula-render.controller.ts b/packages/sheets-formula/src/controllers/formula-render.controller.ts
index e673f0a62a..2c81bcc3b3 100644
--- a/packages/sheets-formula/src/controllers/formula-render.controller.ts
+++ b/packages/sheets-formula/src/controllers/formula-render.controller.ts
@@ -17,7 +17,7 @@
import { LifecycleStages, OnLifecycle, RxDisposable } from '@univerjs/core';
import { Inject } from '@wendellhu/redi';
import { INTERCEPTOR_POINT, SheetInterceptorService } from '@univerjs/sheets';
-import { extractFormulaError } from './utils/utils';
+import { extractFormulaError, extractFormulaNumber } from './utils/utils';
const FORMULA_ERROR_MARK = {
tl: {
@@ -41,6 +41,15 @@ export class FormulaRenderManagerController extends RxDisposable {
INTERCEPTOR_POINT.CELL_CONTENT,
{
handler: (cell, pos, next) => {
+ // Dealing with precision issues
+ const formulaNumber = extractFormulaNumber(cell);
+ if (formulaNumber !== null) {
+ return next({
+ ...cell,
+ v: formulaNumber,
+ });
+ }
+
const errorType = extractFormulaError(cell);
if (!errorType) {
return next(cell);
diff --git a/packages/sheets-formula/src/controllers/utils/__tests__/utils.spec.ts b/packages/sheets-formula/src/controllers/utils/__tests__/utils.spec.ts
index 906c07c9c7..87d3b93a97 100644
--- a/packages/sheets-formula/src/controllers/utils/__tests__/utils.spec.ts
+++ b/packages/sheets-formula/src/controllers/utils/__tests__/utils.spec.ts
@@ -17,7 +17,8 @@
import { describe, expect, it } from 'vitest';
import { ErrorType } from '@univerjs/engine-formula';
-import { extractFormulaError } from '../utils';
+import { CellValueType } from '@univerjs/core';
+import { extractFormulaError, extractFormulaNumber } from '../utils';
describe('Test utils', () => {
it('Function extractFormulaError', () => {
@@ -47,4 +48,11 @@ describe('Test utils', () => {
expect(extractFormulaError(null)).toBeNull();
expect(extractFormulaError(undefined)).toBeNull();
});
+
+ it('Function extractFormulaNumber', () => {
+ const v = 0.07 / 0.1;
+ expect(extractFormulaNumber({ v })).toBeNull();
+ expect(extractFormulaNumber({ v, f: '=SUM(A1)' })).toBeNull();
+ expect(extractFormulaNumber({ v, si: 'id1', f: '=SUM(A1)', t: CellValueType.NUMBER })).toBe(0.7);
+ });
});
diff --git a/packages/sheets-formula/src/controllers/utils/utils.ts b/packages/sheets-formula/src/controllers/utils/utils.ts
index 871f00fdb1..7cfc00761d 100644
--- a/packages/sheets-formula/src/controllers/utils/utils.ts
+++ b/packages/sheets-formula/src/controllers/utils/utils.ts
@@ -15,9 +15,9 @@
*/
import type { ICellData, IContextService, Nullable } from '@univerjs/core';
-import { FOCUSING_DOC, FOCUSING_UNIVER_EDITOR, FOCUSING_UNIVER_EDITOR_STANDALONE_SINGLE_MODE, isFormulaId, isFormulaString } from '@univerjs/core';
+import { CellValueType, FOCUSING_DOC, FOCUSING_UNIVER_EDITOR, FOCUSING_UNIVER_EDITOR_STANDALONE_SINGLE_MODE, isFormulaId, isFormulaString } from '@univerjs/core';
import type { ErrorType } from '@univerjs/engine-formula';
-import { ERROR_TYPE_SET } from '@univerjs/engine-formula';
+import { ERROR_TYPE_SET, stripErrorMargin } from '@univerjs/engine-formula';
export function whenEditorStandalone(contextService: IContextService) {
return (
@@ -34,9 +34,21 @@ export function whenEditorStandalone(contextService: IContextService) {
*/
export function extractFormulaError(cell: Nullable<ICellData>) {
// Must contain a formula
- if (typeof cell?.v === 'string' && (isFormulaString(cell.f) || isFormulaId(cell.si)) && ERROR_TYPE_SET.has(cell.v as ErrorType)) {
+ if ((isFormulaString(cell?.f) || isFormulaId(cell?.si)) && typeof cell?.v === 'string' && ERROR_TYPE_SET.has(cell.v as ErrorType)) {
return cell.v as ErrorType;
}
return null;
}
+
+/**
+ * Extract the formula number from the cell, handle the precision issue
+ * @param cell
+ * @returns
+ */
+export function extractFormulaNumber(cell: Nullable<ICellData>) {
+ if ((isFormulaString(cell?.f) || isFormulaId(cell?.si)) && cell?.t === CellValueType.NUMBER && typeof cell?.v === 'number') {
+ return stripErrorMargin(cell.v);
+ }
+ return null;
+}