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.
TypeScript boardcollaborationdocdocxexceloffce365officepdfpptpptxpresentationsdksheetslidesspreadsheetuniverwordwordprocessorworkspacexlsx
feat(formula): supplement NUMBERSTRING formula (#4615)
wpxp1234567755e263212f
diff --git a/packages/engine-formula/src/functions/text/function-map.ts b/packages/engine-formula/src/functions/text/function-map.tsindex 6cb46bbcbb..32eb2c9a2e 100644--- a/packages/engine-formula/src/functions/text/function-map.ts+++ b/packages/engine-formula/src/functions/text/function-map.ts@@ -36,6 +36,7 @@ import { Lenb } from './lenb';import { Lower } from './lower';import { Mid } from './mid';import { Midb } from './midb';+import { Numberstring } from './numberstring';import { Numbervalue } from './numbervalue';import { Proper } from './proper';import { Regexextract } from './regexextract';@@ -84,6 +85,7 @@ export const functionText = [[Lower, FUNCTION_NAMES_TEXT.LOWER],[Mid, FUNCTION_NAMES_TEXT.MID],[Midb, FUNCTION_NAMES_TEXT.MIDB],+ [Numberstring, FUNCTION_NAMES_TEXT.NUMBERSTRING],[Numbervalue, FUNCTION_NAMES_TEXT.NUMBERVALUE],[Regexextract, FUNCTION_NAMES_TEXT.REGEXEXTRACT],[Regexmatch, FUNCTION_NAMES_TEXT.REGEXMATCH],diff --git a/packages/engine-formula/src/functions/text/function-names.ts b/packages/engine-formula/src/functions/text/function-names.tsindex a457ea9cb5..7e59d28606 100644--- a/packages/engine-formula/src/functions/text/function-names.ts+++ b/packages/engine-formula/src/functions/text/function-names.ts@@ -36,6 +36,7 @@ export enum FUNCTION_NAMES_TEXT {LOWER = 'LOWER',MID = 'MID',MIDB = 'MIDB',+ NUMBERSTRING = 'NUMBERSTRING',NUMBERVALUE = 'NUMBERVALUE',PHONETIC = 'PHONETIC',PROPER = 'PROPER',diff --git a/packages/engine-formula/src/functions/text/numberstring/__test__/index.spec.ts b/packages/engine-formula/src/functions/text/numberstring/__test__/index.spec.tsnew file mode 100644index 0000000000..e51a758052--- /dev/null+++ b/packages/engine-formula/src/functions/text/numberstring/__test__/index.spec.ts@@ -0,0 +1,147 @@+/**+ * 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 { describe, expect, it } from 'vitest';++import { ErrorType } from '../../../../basics/error-type';+import { ArrayValueObject, transformToValueObject } from '../../../../engine/value-object/array-value-object';+import { ErrorValueObject } from '../../../../engine/value-object/base-value-object';+import { NullValueObject, NumberValueObject, StringValueObject } from '../../../../engine/value-object/primitive-object';+import { getObjectValue } from '../../../__tests__/create-function-test-bed';+import { FUNCTION_NAMES_TEXT } from '../../function-names';+import { Numberstring } from '../index';++describe('Test numberstring function', () => {+ const testFunction = new Numberstring(FUNCTION_NAMES_TEXT.NUMBERSTRING);++ describe('numberstring', () => {+ it('Value is normal', () => {+ const number = NumberValueObject.create(123);+ const type = NumberValueObject.create(1);+ const result = testFunction.calculate(number, type);+ expect(getObjectValue(result)).toBe('一百二十三');+ });++ it('Type value test', () => {+ const number = NumberValueObject.create(123);+ const type = NumberValueObject.create(1);+ const result = testFunction.calculate(number, type);+ expect(getObjectValue(result)).toBe('一百二十三');++ const type2 = NumberValueObject.create(2);+ const result2 = testFunction.calculate(number, type2);+ expect(getObjectValue(result2)).toBe('壹佰贰拾叁');++ const type3 = NumberValueObject.create(3);+ const result3 = testFunction.calculate(number, type3);+ expect(getObjectValue(result3)).toBe('一二三');++ const type4 = NumberValueObject.create(4);+ const result4 = testFunction.calculate(number, type4);+ expect(getObjectValue(result4)).toBe(ErrorType.NUM);+ });++ it('Value is string', () => {+ const number = StringValueObject.create('a123');+ const type = NumberValueObject.create(1);+ const result = testFunction.calculate(number, type);+ expect(getObjectValue(result)).toBe(ErrorType.VALUE);++ const number2 = NumberValueObject.create(123);+ const type2 = StringValueObject.create('a1');+ const result2 = testFunction.calculate(number2, type2);+ expect(getObjectValue(result2)).toBe(ErrorType.VALUE);+ });++ it('Value is blank cell', () => {+ const number = NullValueObject.create();+ const type = NumberValueObject.create(1);+ const result = testFunction.calculate(number, type);+ expect(getObjectValue(result)).toBe('〇');+ });++ it('Value is error', () => {+ const number = ErrorValueObject.create(ErrorType.NAME);+ const type = NumberValueObject.create(1);+ const result = testFunction.calculate(number, type);+ expect(getObjectValue(result)).toBe(ErrorType.NAME);++ const number2 = NumberValueObject.create(123);+ const type2 = ErrorValueObject.create(ErrorType.NAME);+ const result2 = testFunction.calculate(number2, type2);+ expect(getObjectValue(result2)).toBe(ErrorType.NAME);+ });++ it('Value is array', () => {+ const number = ArrayValueObject.create({+ calculateValueList: transformToValueObject([+ [123456.7, true],+ [false, ErrorType.NAME],+ ]),+ rowCount: 2,+ columnCount: 2,+ unitId: '',+ sheetId: '',+ row: 0,+ column: 0,+ });+ const type = ArrayValueObject.create({+ calculateValueList: transformToValueObject([+ [1],+ [2],+ [3],+ ]),+ rowCount: 3,+ columnCount: 1,+ unitId: '',+ sheetId: '',+ row: 0,+ column: 0,+ });+ const result = testFunction.calculate(number, type);+ expect(getObjectValue(result)).toStrictEqual([+ ['一十二万三千四百五十七', '一'],+ ['零', ErrorType.NAME],+ [ErrorType.NA, ErrorType.NA],+ ]);+ });++ it('More test', () => {+ let number = NumberValueObject.create(102300000000003);+ let type = NumberValueObject.create(1);+ let result = testFunction.calculate(number, type);+ expect(getObjectValue(result)).toBe('一百〇二兆三千亿〇三');++ number = NumberValueObject.create(10230000000000000);+ result = testFunction.calculate(number, type);+ expect(getObjectValue(result)).toBe('一〇二三〇兆');++ number = NumberValueObject.create(10230);+ result = testFunction.calculate(number, type);+ expect(getObjectValue(result)).toBe('一万〇二百三十');++ number = NumberValueObject.create(102300);+ type = NumberValueObject.create(2);+ result = testFunction.calculate(number, type);+ expect(getObjectValue(result)).toBe('壹拾万贰仟叁佰');++ number = NumberValueObject.create(10000000);+ type = NumberValueObject.create(2);+ result = testFunction.calculate(number, type);+ expect(getObjectValue(result)).toBe('壹仟万');+ });+ });+});diff --git a/packages/engine-formula/src/functions/text/numberstring/index.ts b/packages/engine-formula/src/functions/text/numberstring/index.tsnew file mode 100644index 0000000000..d37c9e93dc--- /dev/null+++ b/packages/engine-formula/src/functions/text/numberstring/index.ts@@ -0,0 +1,151 @@+/**+ * 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 { ArrayValueObject } from '../../../engine/value-object/array-value-object';+import type { BaseValueObject } from '../../../engine/value-object/base-value-object';+import type { NumberValueObject } from '../../../engine/value-object/primitive-object';+import { ErrorType } from '../../../basics/error-type';+import { expandArrayValueObject } from '../../../engine/utils/array-object';+import { ErrorValueObject } from '../../../engine/value-object/base-value-object';+import { StringValueObject } from '../../../engine/value-object/primitive-object';+import { BaseFunction } from '../../base-function';++const chineseLowercaseNumbers = ['〇', '一', '二', '三', '四', '五', '六', '七', '八', '九'];+const chineseUppercaseNumbers = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖'];+const chineseLowercaseUnits = ['', '十', '百', '千'];+const chineseUppercaseUnits = ['', '拾', '佰', '仟'];+const suffixUnits = ['', '万', '亿', '兆'];++export class Numberstring extends BaseFunction {+ override minParams = 2;++ override maxParams = 2;++ override calculate(number: BaseValueObject, type: BaseValueObject): BaseValueObject {+ const maxRowLength = Math.max(+ number.isArray() ? (number as ArrayValueObject).getRowCount() : 1,+ type.isArray() ? (type as ArrayValueObject).getRowCount() : 1+ );++ const maxColumnLength = Math.max(+ number.isArray() ? (number as ArrayValueObject).getColumnCount() : 1,+ type.isArray() ? (type as ArrayValueObject).getColumnCount() : 1+ );++ const numberArray = expandArrayValueObject(maxRowLength, maxColumnLength, number, ErrorValueObject.create(ErrorType.NA));+ const typeArray = expandArrayValueObject(maxRowLength, maxColumnLength, type, ErrorValueObject.create(ErrorType.NA));++ const resultArray = numberArray.mapValue((numberObject, rowIndex, columnIndex) => {+ const typeObject = typeArray.get(rowIndex, columnIndex) as BaseValueObject;++ if (numberObject.isError()) {+ return numberObject;+ }++ if (typeObject.isError()) {+ return typeObject;+ }++ return this._handleSingleObject(numberObject, typeObject);+ });++ if (maxRowLength === 1 && maxColumnLength === 1) {+ return (resultArray as ArrayValueObject).get(0, 0) as BaseValueObject;+ }++ return resultArray;+ }++ // eslint-disable-next-line+ private _handleSingleObject(number: BaseValueObject, type: BaseValueObject): BaseValueObject {+ const _number = number.convertToNumberObjectValue();++ if (_number.isError()) {+ return _number;+ }++ const _type = type.convertToNumberObjectValue();++ if (_type.isError()) {+ return _type;+ }++ let numberValue = (_number as NumberValueObject).getValue();+ const typeValue = Math.trunc((_type as NumberValueObject).getValue());++ if (numberValue < 0 || ![1, 2, 3].includes(typeValue)) {+ return ErrorValueObject.create(ErrorType.NUM);+ }++ numberValue = Math.round(numberValue);++ const numberString = numberValue.toString();+ const len = numberString.length;++ let result = '';+ let hasZero = false;++ for (let i = 0; i < len; i++) {+ const num = Number(numberString[i]);++ // 0+ if (len === 1 && num === 0) {+ result += typeValue === 2 ? chineseUppercaseNumbers[0] : chineseLowercaseNumbers[0];+ break;+ }++ // type is 3, directly return the chinese lowercase equivalent of a number.+ if (typeValue === 3) {+ result += chineseLowercaseNumbers[num];+ continue;+ }++ // type is 1 or 2, return chinese currency format in lowercase or uppercase of a number.+ const pos = len - i - 1;+ const unit = pos % 4;+ const suffixUnit = Math.trunc(pos / 4);++ if (len >= 17 && suffixUnit > 2) {+ result += typeValue === 1 ? chineseLowercaseNumbers[num] : chineseUppercaseNumbers[num];++ if (suffixUnit > 3) {+ continue;+ }+ } else {+ if (num === 0) {+ hasZero = unit !== 0;+ } else {+ if (hasZero) {+ result += typeValue === 1 ? chineseLowercaseNumbers[0] : chineseUppercaseNumbers[0];+ hasZero = false;+ }++ result += typeValue === 1 ? chineseLowercaseNumbers[num] + chineseLowercaseUnits[unit] : chineseUppercaseNumbers[num] + chineseUppercaseUnits[unit];+ }+ }++ if (unit === 0 && suffixUnit > 0) {+ const segment = numberString.slice(Math.max(0, i - 3), i + 1);++ if (segment !== '0000') {+ result += suffixUnits[suffixUnit];+ }+ }+ }++ return StringValueObject.create(result);+ }+}diff --git a/packages/sheets-formula-ui/src/locale/function-list/text/en-US.ts b/packages/sheets-formula-ui/src/locale/function-list/text/en-US.tsindex 232963bd5f..489bb9fcef 100644--- a/packages/sheets-formula-ui/src/locale/function-list/text/en-US.ts+++ b/packages/sheets-formula-ui/src/locale/function-list/text/en-US.ts@@ -305,6 +305,20 @@ export default {numBytes: { name: 'num_bytes', detail: 'Specifies the number of characters you want MIDB to extract, based on bytes.' },},},+ NUMBERSTRING: {+ description: 'Convert numbers to Chinese strings',+ abstract: 'Convert numbers to Chinese strings',+ links: [+ {+ title: 'Instruction',+ url: 'https://www.wps.cn/learning/course/detail/id/340.html?chan=pc_kdocs_function',+ },+ ],+ functionParameter: {+ number: { name: 'number', detail: 'The value converted to a Chinese string.' },+ type: { name: 'type', detail: 'The type of the returned result. \n1. Chinese lowercase \n2. Chinese uppercase \n3. Reading and Writing Chinese Characters' },+ },+ },NUMBERVALUE: {description: 'Converts text to number in a locale-independent manner',abstract: 'Converts text to number in a locale-independent manner',diff --git a/packages/sheets-formula-ui/src/locale/function-list/text/fr-FR.ts b/packages/sheets-formula-ui/src/locale/function-list/text/fr-FR.tsindex 9628859e02..411d1b9e69 100644--- a/packages/sheets-formula-ui/src/locale/function-list/text/fr-FR.ts+++ b/packages/sheets-formula-ui/src/locale/function-list/text/fr-FR.ts@@ -310,6 +310,20 @@ export default {number2: { name: 'nombre2', detail: 'second' },},},+ NUMBERSTRING: {+ description: 'Convertir des nombres en chaînes chinoises',+ abstract: 'Convertir des nombres en chaînes chinoises',+ links: [+ {+ title: 'guide',+ url: 'https://www.wps.cn/learning/course/detail/id/340.html?chan=pc_kdocs_function',+ },+ ],+ functionParameter: {+ number: { name: 'numérique', detail: 'La valeur numérique convertie en chaîne chinoise.' },+ type: { name: 'type', detail: 'Le type du résultat renvoyé. \n1. Minuscules chinoises \n2. Mettre les caractères chinois en majuscules \n3. Lire et écrire des caractères chinois' },+ },+ },NUMBERVALUE: {description: 'Converts text to number in a locale-independent manner',abstract: 'Converts text to number in a locale-independent manner',diff --git a/packages/sheets-formula-ui/src/locale/function-list/text/ja-JP.ts b/packages/sheets-formula-ui/src/locale/function-list/text/ja-JP.tsindex c852c426de..6be0879e57 100644--- a/packages/sheets-formula-ui/src/locale/function-list/text/ja-JP.ts+++ b/packages/sheets-formula-ui/src/locale/function-list/text/ja-JP.ts@@ -306,6 +306,20 @@ export default {numBytes: { name: 'バイト数', detail: '取り出す文字数をバイト数で指定します。' },},},+ NUMBERSTRING: {+ description: '数字を中国語の文字列に変換する',+ abstract: '数字を中国語の文字列に変換する',+ links: [+ {+ title: '指導',+ url: 'https://www.wps.cn/learning/course/detail/id/340.html?chan=pc_kdocs_function',+ },+ ],+ functionParameter: {+ number: { name: '数値', detail: '中国語の文字列に変換される数値。' },+ type: { name: 'タイプ', detail: '返される結果のタイプ。\n1. 中国語小文字 \n2. 中国語の文字を大文字にする \n3. 漢字の読み書き' },+ },+ },NUMBERVALUE: {description: '文字列をロケールに依存しない方法で数値に変換します。',abstract: '文字列をロケールに依存しない方法で数値に変換します。',diff --git a/packages/sheets-formula-ui/src/locale/function-list/text/ru-RU.ts b/packages/sheets-formula-ui/src/locale/function-list/text/ru-RU.tsindex b402c62501..571f2467f0 100644--- a/packages/sheets-formula-ui/src/locale/function-list/text/ru-RU.ts+++ b/packages/sheets-formula-ui/src/locale/function-list/text/ru-RU.ts@@ -305,6 +305,20 @@ export default {numBytes: { name: 'количество_байтов', detail: 'Указывает в байтах количество символов, извлекаемых функцией MIDB.' },},},+ NUMBERSTRING: {+ description: 'Преобразовать числа в китайские строки',+ abstract: 'Преобразовать числа в китайские строки',+ links: [+ {+ title: 'Инструкция',+ url: 'https://www.wps.cn/learning/course/detail/id/340.html?chan=pc_kdocs_function',+ },+ ],+ functionParameter: {+ number: { name: 'Числовой', detail: 'Числовое значение, преобразуемое в китайскую строку.' },+ type: { name: 'тип', detail: 'Тип возвращаемого результата. \n1. Китайские иероглифы в нижнем регистре \n2. Китайские иероглифы в верхнем регистре \n3. Чтение и написание китайских иероглифов' },+ },+ },NUMBERVALUE: {description: 'Преобразует текст в число независимо от региональных стандартов',abstract: 'Преобразует текст в число независимо от региональных стандартов',diff --git a/packages/sheets-formula-ui/src/locale/function-list/text/vi-VN.ts b/packages/sheets-formula-ui/src/locale/function-list/text/vi-VN.tsindex 6b7cc92f30..dd9d915f5b 100644--- a/packages/sheets-formula-ui/src/locale/function-list/text/vi-VN.ts+++ b/packages/sheets-formula-ui/src/locale/function-list/text/vi-VN.ts@@ -305,6 +305,20 @@ export default {numBytes: { name: 'số Byte', detail: 'Chỉ rõ số ký tự mà bạn muốn hàm MIDB trích xuất, dựa trên byte.' },},},+ NUMBERSTRING: {+ description: 'Chuyển đổi số sang chuỗi tiếng Trung',+ abstract: 'Chuyển đổi số sang chuỗi tiếng Trung',+ links: [+ {+ title: 'Hướng dẫn',+ url: 'https://www.wps.cn/learning/course/detail/id/340.html?chan=pc_kdocs_function',+ },+ ],+ functionParameter: {+ number: { name: 'số', detail: 'Giá trị được chuyển đổi thành chuỗi tiếng Trung.' },+ type: { name: 'kiểu', detail: 'Kiểu kết quả trả về.\n1. chữ thường Trung Quốc \n2. Viết hoa chữ Hán \n3. Đọc và viết chữ Hán' },+ },+ },NUMBERVALUE: {description: 'Chuyển văn bản sang số, theo cách độc lập vị trí.',abstract: 'Chuyển văn bản sang số, theo cách độc lập vị trí.',diff --git a/packages/sheets-formula-ui/src/locale/function-list/text/zh-CN.ts b/packages/sheets-formula-ui/src/locale/function-list/text/zh-CN.tsindex c57b9a3f83..b51f70fa9a 100644--- a/packages/sheets-formula-ui/src/locale/function-list/text/zh-CN.ts+++ b/packages/sheets-formula-ui/src/locale/function-list/text/zh-CN.ts@@ -305,6 +305,20 @@ export default {numBytes: { name: '字节数', detail: '按字节指定要由 MIDB 提取的字符的数量。' },},},+ NUMBERSTRING: {+ description: '将数字转换为中文字符串',+ abstract: '将数字转换为中文字符串',+ links: [+ {+ title: '教学',+ url: 'https://www.wps.cn/learning/course/detail/id/340.html?chan=pc_kdocs_function',+ },+ ],+ functionParameter: {+ number: { name: '数值', detail: '被转化为中文字符串的数值。' },+ type: { name: '类型', detail: '返回结果的类型。\n1. 汉字小写 \n2. 汉字大写 \n3. 汉字读写' },+ },+ },NUMBERVALUE: {description: '以与区域设置无关的方式将文本转换为数字',abstract: '以与区域设置无关的方式将文本转换为数字',diff --git a/packages/sheets-formula-ui/src/locale/function-list/text/zh-TW.ts b/packages/sheets-formula-ui/src/locale/function-list/text/zh-TW.tsindex eedeb40aa7..469a1ef875 100644--- a/packages/sheets-formula-ui/src/locale/function-list/text/zh-TW.ts+++ b/packages/sheets-formula-ui/src/locale/function-list/text/zh-TW.ts@@ -304,6 +304,20 @@ export default {numBytes: { name: '字節數', detail: '指定要 MIDB 擷取的字元數目,以位元組為單位。' },},},+ NUMBERSTRING: {+ description: '將數字轉換為中文字符串',+ abstract: '將數字轉換為中文字符串',+ links: [+ {+ title: '教導',+ url: 'https://www.wps.cn/learning/course/detail/id/340.html?chan=pc_kdocs_function',+ },+ ],+ functionParameter: {+ number: { name: '數值', detail: '被轉換為中文字符串的數值。' },+ type: { name: '類型', detail: '傳回結果的類型。\n1. 漢字小寫 \n2. 漢字大寫 \n3. 漢字讀寫' },+ },+ },NUMBERVALUE: {description: '以與區域設定無關的方式將文字轉換為數字',abstract: '以與區域設定無關的方式將文字轉換為數字',diff --git a/packages/sheets-formula/src/services/function-list/text.ts b/packages/sheets-formula/src/services/function-list/text.tsindex 71aa172542..67880c8d0c 100644--- a/packages/sheets-formula/src/services/function-list/text.ts+++ b/packages/sheets-formula/src/services/function-list/text.ts@@ -14,7 +14,8 @@* limitations under the License.*/-import { FUNCTION_NAMES_TEXT, FunctionType, type IFunctionInfo } from '@univerjs/engine-formula';+import type { IFunctionInfo } from '@univerjs/engine-formula';+import { FUNCTION_NAMES_TEXT, FunctionType } from '@univerjs/engine-formula';export const FUNCTION_LIST_TEXT: IFunctionInfo[] = [{@@ -451,6 +452,28 @@ export const FUNCTION_LIST_TEXT: IFunctionInfo[] = [},],},+ {+ functionName: FUNCTION_NAMES_TEXT.NUMBERSTRING,+ functionType: FunctionType.Text,+ description: 'formula.functionList.NUMBERSTRING.description',+ abstract: 'formula.functionList.NUMBERSTRING.abstract',+ functionParameter: [+ {+ name: 'formula.functionList.NUMBERSTRING.functionParameter.number.name',+ detail: 'formula.functionList.NUMBERSTRING.functionParameter.number.detail',+ example: '123',+ require: 1,+ repeat: 0,+ },+ {+ name: 'formula.functionList.NUMBERSTRING.functionParameter.type.name',+ detail: 'formula.functionList.NUMBERSTRING.functionParameter.type.detail',+ example: '1',+ require: 1,+ repeat: 0,+ },+ ],+ },{functionName: FUNCTION_NAMES_TEXT.NUMBERVALUE,functionType: FunctionType.Text,