{"id":20623503,"url":"https://github.com/gxlmyacc/formula-calc","last_synced_at":"2026-02-23T00:04:39.641Z","repository":{"id":241451634,"uuid":"806492285","full_name":"gxlmyacc/formula-calc","owner":"gxlmyacc","description":"formula-calc is a library for formula calculation through strings for javascript","archived":false,"fork":false,"pushed_at":"2025-02-20T01:50:29.000Z","size":1029,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-03-28T20:21:18.418Z","etag":null,"topics":["calculations","decimal","formula","formula-calculator","javascript","string-calculator","typescript"],"latest_commit_sha":null,"homepage":"","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/gxlmyacc.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2024-05-27T09:54:08.000Z","updated_at":"2025-02-20T01:50:33.000Z","dependencies_parsed_at":"2024-07-17T09:04:31.215Z","dependency_job_id":"22244416-cf37-4e36-97a9-ace16a88ca27","html_url":"https://github.com/gxlmyacc/formula-calc","commit_stats":null,"previous_names":["gxlmyacc/formula-calc"],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/gxlmyacc%2Fformula-calc","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/gxlmyacc%2Fformula-calc/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/gxlmyacc%2Fformula-calc/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/gxlmyacc%2Fformula-calc/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/gxlmyacc","download_url":"https://codeload.github.com/gxlmyacc/formula-calc/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":249023746,"owners_count":21199961,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["calculations","decimal","formula","formula-calculator","javascript","string-calculator","typescript"],"created_at":"2024-11-16T12:27:25.750Z","updated_at":"2025-10-25T20:17:57.011Z","avatar_url":"https://github.com/gxlmyacc.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# formula-calc\n\nformula-calc is a library for formula calculation through strings for javascript/typescript.\n\n\n[![NPM version](https://img.shields.io/npm/v/formula-calc.svg?style=flat)](https://npmjs.com/package/formula-calc)\n[![NPM downloads](https://img.shields.io/npm/dm/formula-calc.svg?style=flat)](https://npmjs.com/package/formula-calc)\n[![Coverage Status](https://coveralls.io/repos/github/gxlmyacc/formula-calc/badge.svg?branch=main)](https://coveralls.io/github/gxlmyacc/formula-calc?branch=main)\n\nNote: The internal numerical calculation uses the [decimal.js](https://mikemcl.github.io/decimal.js/) library.\n\n## [中文说明](https://github.com/gxlmyacc/formula-calc/blob/main/README_CN.md)\n\n## Main Features\n\n1. Basic Calculations: Supports basic mathematical operations such as addition, subtraction, multiplication, division, exponentiation, and modulus.\n\n2. Variable Support: Allows parameters to be passed through objects or arrays, supporting optional parameters and ternary operations.\n\n3. Built-in Functions: Provides various built-in functions like max, min, sum, avg, round, etc.\n\n4. Custom Functions: Users can define their own functions to extend the library's functionality.\n\n5. Asynchronous Support: Supports Promise calculations, allowing for the handling of asynchronous parameters.\n\n6. Precision Control: Users can set the precision of calculations and the precision for each step.\n\n7. Type Conversion: Supports converting values to strings, numbers, and booleans.\n\n8. Null Value Handling: Can treat `null`, `undefined`, `NaN`, `empty string` as zero.\n\n9. Result referencing: Supports referencing the results of calculations in order using `$1...$n`, similar to regular expressions.\n\n\n## Install\n\n```bash\nnpm install --save formula-calc\n```\nor\n```bash\nyarn add formula-calc\n```\n\n## Usage\n\n1. basic\n\n```js\nimport formulaCalc from 'formula-calc';\n\nconst result = formulaCalc('1 + 1');\nconsole.log(result); // 2\nconst result = formulaCalc('1 - 1');\nconsole.log(result); // 0\nconst result = formulaCalc('2 * 3');\nconsole.log(result); // 6\nconst result = formulaCalc('4 / 2');\nconsole.log(result); // 2\n\n\n// calculate with power\nconst result = formulaCalc('5 ^ 2');\nconsole.log(result); // 25\n\n// calculate with percent\nconst result = formulaCalc('2% + 1')\nconsole.log(result); // 1.02\n\n// divide to integer\nconst result = formulaCalc('5 // 4');\nconsole.log(result); // 1\nconst result = formulaCalc(' -1.1 // 6');\nconsole.log(result); // 0\n\n// calculate with mod\nconst result = formulaCalc('5 % 2')\nconsole.log(result); // 1\n\n// with parenthesis\nconst result = formulaCalc('4 * (1 + 1) + 2')\nconsole.log(result); // 10\n\n```\n\n2. with variable\n\n```js\nimport formulaCalc, { createFormula } from 'formula-calc';\n\n// get param from object\nconst result = formulaCalc('a + b.c', { \n  params: { \n    a: 1, \n    b: {\n      c: 2\n    }\n  }\n });\nconsole.log(result); // 3\n\n// get param from array\nconst result = formulaCalc('a + b.c.1', { \n  params: { \n    a: 1, \n    b: {\n      c: [1, 2, 3]\n    }\n  }\n });\nconsole.log(result); // 3\n\n// optional parameter\nconst result = formulaCalc('a.b?.c', { \n  params: { \n    a: {\n      b: 1\n    }, \n  }\n });\nconsole.log(result); // 1\n\n// optional parameter in ternary operator\nconst result = formulaCalc('a.b?.c ? 1 : 2', { \n  params: { \n    a: {\n      b: {}\n    }, \n  }\n });\nconsole.log(result); // 2\n\n\n// calc with params list\nconst result = formulaCalc('a + 1', { \n  params: [\n    { a: 1 },\n    { a: 2 },\n    { a: 3 },\n  ]\n });\nconsole.log(result); // [2, 3, 4]\n\n// calc with formula instance\nconst formula = createFormula('a + 1');\nconst result = formulaCalc(formula, {\n  params: {\n    a: 1\n  }\n});\nconsole.log(result); // 2\n\n// with promise\nconst result = await formulaCalc('a + 1', { \n  params: { \n    a: Promise.resolve(2),\n  }\n });\nconsole.log(result); // 3\n\n```\n\n3. with function, built in functions: add, avg, ceil, eval, exist, floor, if, max, min, noref, random, round, sqrt, sum, trunc\n\n```js\nimport formulaCalc from 'formula-calc';\n\nconst result = formulaCalc('max(1, 2, 3, 4, 5)');\nconsole.log(result); // 5\n\nconst result = formulaCalc('min(1, 2, 3, 4, 5)');\nconsole.log(result); // 1\n\nconst result = formulaCalc('abs(-1)');\nconsole.log(result); // 1\n\nconst result = formulaCalc('sum(1, 2, 3, 4, 5)');\nconsole.log(result); // 15\n\nconst result = formulaCalc('sum(1, 2, 3, 4, a)', {\n  params: {\n    a: [5, 6, 7, 8]\n  }\n});\nconsole.log(result); // 36\n\nconst result = formulaCalc('round(2.335)');\nconsole.log(result); // 2.34\n\nconst result = formulaCalc('round(2.335, 1)');\nconsole.log(result); // 2.3\n\nconst result = formulaCalc('if(a, 1, 2)', {\n  params: {\n    a: true\n  }\n});\nconsole.log(result); // 1\n\nconst result = formulaCalc('if(a, 1, 2)', {\n  params: {\n    a: false\n  }\n});\nconsole.log(result); // 2\n\nconst result = formulaCalc('a ? 1 : 2', {\n  params: {\n    a: true\n  }\n});\nconsole.log(result); // 1\n\nconst result = formulaCalc('a ? 1 : 2', {\n  params: {\n    a: false\n  }\n});\nconsole.log(result); // 2\n\n// with ref: like regex, $1...$n will match the ordinal of parentheses that do not contain functions\nconst result = formulaCalc(\n`if(\n  (a + 2) \u003e 0, \n  $1, \n  0 - $1\n)`, {\n  params: {\n    a: -3\n  }\n});\nconsole.log(result); // 1\n\n```\n\n4. with ref: like regex, $1...$n will match the ordinal of parentheses that do not contain functions\n\n```js\n\nconst result = formulaCalc(\n`if(\n  (a + 2) \u003e 0, \n  $1, \n  0 - $1\n)`, {\n  params: {\n    a: -3\n  }\n});\nconsole.log(result); // 1\n\n```\n\n5. with custom function \n\n```js\nimport formulaCalc from 'formula-calc';\n\nconst result = formulaCalc('add1(2.11)', {\n  customFunctions: {\n    add1: {\n      argMin: 1,\n      argMax: 1,\n      execute(params) {\n        return params[0] + 1;\n      }\n    }\n  }\n});\nconsole.log(result); // 3.11\n\n```\n\n6. with eval\n\n```js\nimport formulaCalc from 'formula-calc';\n\nconst result = formulaCalc(\n`if(\n  a \u003e 0, \n  eval(planA), \n  eval(planB)\n)`, {\n  params: {\n    a: -3,\n    planA: 'a + 1',\n    planB: '0 - a + 1',\n  }\n});\nconsole.log(result); // 4\n\n```\n\n7. handle precision\n\n```js\nimport formulaCalc from 'formula-calc';\n\nconst result = formulaCalc('10 / 3');\nconsole.log(result); // 3.3333333333333\n\nconst result = formulaCalc('10 / 3', { precision: 2 });\nconsole.log(result); // 3.33\n\n```\n\n8. rounding at each step of the operation\n\n```js\nimport formulaCalc from 'formula-calc';\n\nconst result = formulaCalc('3.334 + 3.335', {\n  stepPrecision: true,\n});\nconsole.log(result); // 6.67\n\nconst result = formulaCalc('3.3334 + 3.3315', {\n  precision: 2,\n  stepPrecision: 3,\n};\nconsole.log(result); // 6.67\n\n```\n\n9. cast value\n\n```js\nimport formulaCalc from 'formula-calc';\n\nconst result = formulaCalc('string(1)');\nconsole.log(result); // '1'\n\nconst result = formulaCalc('string(a)', { params: { a: undefined } });\nconsole.log(result); // ''\n\nconst result = formulaCalc('number(\"1\")');\nconsole.log(result); // 1\n\nconst result = formulaCalc('boolean(1)');\nconsole.log(result); // true\n\nconst result = formulaCalc('boolean(0)');\nconsole.log(result); // false\n\n```\n\n10. null as zero\n\n```js\nimport formulaCalc from 'formula-calc';\n\nconst result = formulaCalc('a.b.c', {\n  params: {\n    a: {}\n  },\n  nullAsZero: true\n});\nconsole.log(result); // 0\n\n// empty string as zero\nconst result = formulaCalc('1 + a.b', {\n  params: {\n    a: {\n      b: ''\n    }\n  },\n  nullAsZero: true\n});\nconsole.log(result); // 1\n\n```\n\n## Documentation\n\n### API\n\n#### formulaCalc\n\n`formulaCalc` is the default export method. It is the core function for performing formula calculations.\n\n```tsx\ntype RoundingType = 'UP'|'DOWN'|'CEIL'|'FLOOR'|'HALF_UP'|'HALF_DOWN'|'HALF_EVEN'|'HALF_CEIL'|'HALF_FLOOR'|'EUCLID';\n\ntype FormulaValueOptions = {\n  Decimal?: typeof Decimal,\n  precision?: number,\n  rounding?: RoundingType,\n  stepPrecision?: boolean|number,\n  tryStringToNumber?: boolean,\n  ignoreRoundingOriginalValue?: boolean,\n  ignoreRoundingParams?: boolean|(name: string) =\u003e boolean,\n  returnDecimal?: boolean,\n  nullAsZero?: boolean,\n  nullIfParamNotFound?: boolean,\n  eval?: null|((expr: string, dataSource: IFormulaDataSource, options: FormulaValueOptions, forArithmetic?: boolean) =\u003e any),\n  onTrace?: (item: IFormulaValue, value: any) =\u003e void,\n}\n\ninterface FormulaOptions extends FormulaValueOptions {\n\n}\n\ninterface FormulaCreateOptions extends FormulaOptions {\n  customFunctions?: Record\u003cstring, FormulaCustomFunctionItem\u003e,\n}\n\ninterface FormulaCalcCommonOptions extends FormulaCreateOptions {\n  dataSource?: IFormulaDataSource\n}\n\ninterface FormulaCalcOptions extends FormulaOptions {\n  params?: FormulaCalcParams|Array\u003cFormulaCalcParams\u003e,\n  onFormulaCreated?: (formula: Formula) =\u003e void,\n  cache?: boolean,\n}\n\ndeclare function formulaCalc\u003cT extends any = any\u003e(\n  expressionOrFormula: string|Formula,\n  options: FormulaCalcOptions = {},\n  returnReferenceType?: T|((result: any) =\u003e T)\n): T;\n\nexport default formulaCalc;\n```\n\n##### expressionOrFormula\n\nSupports the following types:\n\n- Expression strings, such as: `a + b`.\n\n- Formula instances. You can create them using `new Formula()`. If you need to perform a large number of repeated calculations on the same expression, it is recommended to use formula instances, as they cache the parsing result of the expression to improve execution performance.\n\nuse formula instance:\n```ts\nimport formulaCalc from 'formula-calc';\n\nconst formula = new Formula();\nformula.parse('1 + a');\n\nconst result = [1, 2, 3].map(a =\u003e formulaCalc(formula, { params: { a } }));\nconsole.log(result); // [2, 3, 4]\n\n```\nyou can also use params list to execute multiple times:\n\n```ts\nimport formulaCalc from 'formula-calc';\nconst result = formulaCalc('1 + a', { params: [1, 2, 3].map(a =\u003e ({ a }))  });\nconsole.log(result); // [2, 3, 4]\n```\n\n##### options\n\nThe following is a tabular description of the parameters supported by options in formulaCalc:\n\n| Parameter Name | Type | Default Value | Description |\n|---------------------------|----------------------------------------|-----------|--------------------------------------------------------------|\n| params | FormulaCalcParams\\| Array\\\u003cFormulaCalcParams\\\u003e | - | Parameters passed to the expression, which can be an object or an array. If it is an array, each object in the array will be traversed to execute the expression, returning an array of results. |\n| dataSource | IFormulaDataSource | - | Custom data source passed to the expression. If not provided, the default data source (which handles the retrieval of params) will be used. If provided, the retrieval of params will be handled by the user. |\n| customFunctions | Record\\\u003cstring, FormulaCustomFunctionItem\\\u003e | - | Custom function mapping table for registering custom functions. |\n| onFormulaCreated | (formula: Formula) =\u003e void | - | Callback function executed after creating the formula instance. |\n| cache | boolean | false | Whether to cache the formula instance, default is false. If true, instances of the same expression will be cached, and the next call to the same expression will return the cached instance without recreating it. |\n| Decimal | typeof Decimal | - | Custom instance of Decimal.js used for numerical calculations. |\n| precision | number | 2 | Sets the precision of the calculation results. |\n| rounding | RoundingType | 'HALF_UP' | Sets the rounding type. Optional values include: UP, DOWN, CEIL, FLOOR, HALF_UP, HALF_DOWN, HALF_EVEN, HALF_CEIL, HALF_FLOOR, EUCLID. |\n| stepPrecision | boolean \\| number | - | Whether to round at each step of the operation, or set the precision for each step. |\n| stepPrecisionIgnorePercent | boolean | false | Whether to ignore percentage operations in step-by-step rounding. Percentage numbers are often very small and have a significant impact on precision. In certain cases, you can set this to true to ignore the effect of stepPrecision on percentage operations. |\n| tryStringToNumber | boolean | false | Whether to attempt to convert strings to numbers. |\n| ignoreRoundingOriginalValue | boolean | false | Whether to ignore rounding of primitive values (number, string, boolean, params, ref). |\n| ignoreRoundingParams | boolean \\|(name) =\u003e boolean | false | Whether to ignore rounding of parameters. |\n| returnDecimal | boolean | false | Whether to return the number type as Decimal type. |\n| nullAsZero | boolean | false | Whether to treat null, undefined, NaN, and empty strings as zero in calculations. |\n| nullIfParamNotFound | boolean | false | Whether to return null if a parameter is not found. If false, an exception will be thrown when a parameter is not found. |\n| eval | null\\|Function | - | Custom expression eval function. |\n| onTrace | null\\|Function | - | custom trace function. |\n\n###### returnReferenceType\n\nThe return value type of `formulaCalc` can be referenced in the parameters. In js code, users can set `returnReferenceType` to the corresponding type to facilitate IDE type hints.\n\nlike this:\n\n```js\n/** IDE should be able to automatically recognize that the result is of type number  */\nconst result = formulaCalc('1 + 1', {}, 0);\n```\n\nIf `returnReferenceType` is a function, it can process the result value before formulaCalc returns, and the return value of that function will be the final return value.\n\n#### onTrace\n\nIf you need to get the calculation process, you can configure the `onTrace` function to customize the output of the calculation process.\n\ndemo：\n```js\nconst executed = [];\nconst result = formulaCalc('(1 + 1)', {\n  onTrace(item, value) {\n    console.log(`[${item.line}, ${item.column}]: ${item.origText} =`, value);\n  }\n});\nconsole.log(result);\n\n/* \n * console output:\n *  [1, 2]: 1 = 1\n *  [1, 6]: 1 = 1\n *  [1, 2]: 1 + 1 = 2\n *  [1, 1]: (1 + 1) = 2\n *  2\n */\n```\n\n#### formulaUtils\n\n`formulaUtils` is a set of helper utility functions (`sum`, `avg`, `min`, `max`, `round`) designed to facilitate simple calculations that don't need to be performed through expressions.\n\n```tsx\ntype FormulaUtilsParam = number|string|null|undefined|Decimal;\ntype FormulaUtilsOptions = Omit\u003cFormulaCalcOptions, 'params'|'onCreateParam'\u003e;\n\ntype FormulaUtils = {\n  sum: (params: Array\u003cFormulaUtilsParam\u003e, options?: FormulaUtilsOptions) =\u003e number,\n  avg: (params: Array\u003cFormulaUtilsParam\u003e, options?: FormulaUtilsOptions) =\u003e number,\n  min: (params: Array\u003cFormulaUtilsParam\u003e, options?: FormulaUtilsOptions) =\u003e number,\n  max: (params: Array\u003cFormulaUtilsParam\u003e, options?: FormulaUtilsOptions) =\u003e number,\n  \n  add(a: FormulaUtilsParam, b: FormulaUtilsParam, options?: FormulaUtilsOptions) =\u003e number,\n  sub(a: FormulaUtilsParam, b: FormulaUtilsParam, options?: FormulaUtilsOptions) =\u003e number,\n  mul(a: FormulaUtilsParam, b: FormulaUtilsParam, options?: FormulaUtilsOptions) =\u003e number,\n  div(a: FormulaUtilsParam, b: FormulaUtilsParam, options?: FormulaUtilsOptions) =\u003e number,\n  divToInt(a: FormulaUtilsParam, b: FormulaUtilsParam, options?: FormulaUtilsOptions) =\u003e number,\n  pow(a: FormulaUtilsParam, b: FormulaUtilsParam, options?: FormulaUtilsOptions) =\u003e number,\n  mod(a: FormulaUtilsParam, b: FormulaUtilsParam, options?: FormulaUtilsOptions) =\u003e number,\n\n  abs(a: FormulaUtilsParam, options?: FormulaUtilsOptions) =\u003e number,\n  ceil(a: FormulaUtilsParam, options?: FormulaUtilsOptions) =\u003e number,\n  floor(a: FormulaUtilsParam, options?: FormulaUtilsOptions) =\u003e number,\n  trunc(a: FormulaUtilsParam, options?: FormulaUtilsOptions) =\u003e number,\n  sqrt(a: FormulaUtilsParam, options?: FormulaUtilsOptions) =\u003e number,\n  cbrt(a: FormulaUtilsParam, options?: FormulaUtilsOptions) =\u003e number,\n  \n  clamp(a: FormulaUtilsParam, min: FormulaUtilsParam, max: FormulaUtilsParam, options?: FormulaUtilsOptions) =\u003e number,\n\n  round: (\n    value: Decimal.Value,\n    decimalPlaces: number = 2,\n    rounding: Decimal.Rounding|RoundingType = Decimal.ROUND_HALF_UP,\n  ) =\u003e number,\n\n  toFixed: (\n    value: Decimal.Value|null|undefined, \n    options: {\n      precision?: number|[min: number, max: number],\n      comma?: boolean,\n      commaStr?: string,\n      nullStr?: string,\n      trimTrailingZero?: boolean,\n      trimTrailingZeroIfInt?: boolean,\n      rounding?: Decimal.Rounding|RoundingType,\n    } = {}\n  ) =\u003e number,\n}\n\ndeclare const formulaUtils: FormulaUtils;\n\nexport {\n  formulaUtils\n}\n```\nNote: The `sum`, `avg`, `min`, and `max` functions in `formulaUtils` are configured by default with `nullAsZero`, `tryStringToNumber`, and `nullIfParamNotFound` set to `true`.\n\nBelow is an example:\n\n```ts\nimport { formulaUtils } from 'formula-calc';\n\nconst result = formulaUtils.sum([1, 2, 3]);\nconsole.log(result); // 6\n\nconst result = formulaUtils.sum([1, 2, 3, null, undefined, '']);\nconsole.log(result); // 6\n\nconst result = formulaUtils.sum([]);\nconsole.log(result); // 0\n\nconst result = formulaUtils.avg([1, 2, 3]);\nconsole.log(result); // 2\n\nconst result = formulaUtils.avg([]);\nconsole.log(result); // 0\n\nconst result = formulaUtils.min([1, 2, 3]);\nconsole.log(result); // 1\n\nconst result = formulaUtils.min([]);\nconsole.log(result); // 0\n\nconst result = formulaUtils.max([1, 2, 3]);\nconsole.log(result); // 3\n\nconst result = formulaUtils.max([]);\nconsole.log(result); // 0\n\nconst result = formulaUtils.round(1.2345, 3);\nconsole.log(result); // 1.235\n\n```\n\n##### formulaUtils.toFixed\n\n`formulaUtils.toFixed` is a utility function used to format numbers. It converts a number to a string and adds thousand separators, decimal points, precision, etc. Its `options` parameter supports the following formatting options:\n\n| Parameter Name | Type | Default Value | Description |\n|----------|------|--------|------|\n| precision | number \\| [min: number, max: number] | - | Sets the precision. Can be a single number or an array containing minimum and maximum precision values. |\n| comma | boolean | false | Whether to add a thousands separator in the number. |\n| commaStr | string | ',' | The string used as the thousands separator, defaults to a comma. |\n| commaDigit | number | 3 | The thousands separator is added every `commaDigit` digits. |\n| nullStr | string | '' | The string returned If the value is `null`, `undefined`, `NaN`, `Infinity`, or other content that cannot be converted to a numeric type. |\n| trimTrailingZero | boolean | false | Whether to trim trailing zeros after the decimal point. |\n| trimTrailingZeroIfInt | boolean | false | Whether to trim trailing zeros after the decimal point if the value is an integer. |\n| rounding | Decimal.Rounding \\| RoundingType | Decimal.ROUND_HALF_UP | Sets the rounding type. Optional values include: UP, DOWN, CEIL, FLOOR, HALF_UP, HALF_DOWN, HALF_EVEN, HALF_CEIL, HALF_FLOOR, EUCLID. |\n\n```ts\nimport { formulaUtils } from 'formula-calc';\n\nconst result = formulaUtils.toFixed(1.2);\nconsole.log(result); // '1.20'\n\nconst result = formulaUtils.toFixed(1.2, { precision: 3 });\nconsole.log(result); // '1.200'\n\nconst result = formulaUtils.toFixed(1.2, { precision: [2, 4] });\nconsole.log(result); // '1.20'\n\nconst result = formulaUtils.toFixed(1.234, { precision: [2, 4] });\nconsole.log(result); // '1.234'\n\nconst result = formulaUtils.toFixed(1.23456, { precision: [2, 4] });\nconsole.log(result); // '1.2346'\n\nconst result = formulaUtils.toFixed(1.23456, { precision: [2, 4], rounding: 'FLOOR' });\nconsole.log(result); // '1.2345'\n\nconst result = formulaUtils.toFixed(1000.2, { comma: true });\nconsole.log(result); // '1,000.20'\n\nconst result = formulaUtils.toFixed(100000.2, { comma: true, commaDigit: 4, commaStr: '`' });\nconsole.log(result); // '10`0000.20'\n\nconst result = formulaUtils.toFixed(null, { nullStr: '--' });\nconsole.log(result); // '--'\n\nconst result = formulaUtils.toFixed(1);\nconsole.log(result); // '1.00'\n\nconst result = formulaUtils.toFixed(1, { trimTrailingZeroIfInt: true });\nconsole.log(result); // '1'\n\nconst result = formulaUtils.toFixed(1.2, { trimTrailingZeroIfInt: true });\nconsole.log(result); // '1.20'\n\n```\n\n## Values\n\nSupports the following values\n\n- `number` - number, like 1, 2, 3, 1e3, 1e+3, 1e-3\n\n- `string` - string, it is quoted with `\"`, like \"1\", \"2\", \"3\"\n\n- `boolean` - boolean, like true, false\n\n- `null` - null, `undefined` also be as `null`. `null` will be converted to `0` when `nullAsZero` is `true`.\n\n- `NaN` - NaN\n\n- `Infinity` - Infinity\n\n- `params` - params, like `a`, `a.b`, `a.b.0`, \"params\" is taken from the \"params\" parameter in the second parameter of the `formulaCalc` method. If the `param` name contains special characters, it can be quoted with `'`, like this: `'a()*_(\u0026_\u0026*)b'`\n\n- `ref` - `$1`...`$99`, similar to regular expressions, it will match the ordinal of parentheses that do not contain functions\n\n## Operators\n\nSupports the following operators\n\n- `+`  -  add\n\n- `-`  -  subtract\n\n- `*`  -  multiply\n\n- `/`  -  divide\n\n- `//`  -  divide to integer, like `6 // 3` is `2`, `5 // 4` is `1`, if `a` is negative, the result will be `0`, like `-1.1 // 6` is `0`\n\n- `^`  -  power\n\n- `%`  -  mod\n\n- `=` or `==`  -  equal, like `a = b`, if `a` or `b` is `undefined`, it will be as `null`\n\n- `!=` or `\u003c\u003e`  -  not equal\n\n- `\u003e`  -  greater than\n\n- `\u003e=`  -  greater than or equal to\n\n- `\u003c`  -  less than\n\n- `\u003c=`  -  less than or equal to\n\n- `\u0026` or `\u0026\u0026`  -  and\n\n- `|` or `||`  -  or\n\n- `!`  -  not\n\n- `? :`  -  ternary operator, like `a ? b : c`\n\n- `()` -  parenthesis\n\n\nNote: \n- For the comparison operators (`=`, `!=`, `\u003c\u003e`, `\u003e`, `\u003c`, `\u003e=`, `\u003c=`), before performing the comparison, if one side is a number, both sides will be attempted to be converted to numbers for comparison; otherwise, string comparison will be performed. For example, `10 \u003e \"2\"` is true, while `\"10\" \u003e \"2\"` is false. If the `tryStringToNumber` option is set to `true`, then will attempt to convert both sides of the comparison to numbers.\n\n## Functions\n\nSupports the following built in functions:\n\n### Basic Functions\n- `abs(x)` - Returns the absolute value of x\n\n- `ceil(x)` - Rounds x up to the nearest integer\n\n- `floor(x)` - Rounds x down to the nearest integer\n\n- `round(x, y?)` - Rounds x to y decimal places (defaults to `2`)\n\n- `trunc(x)` - Removes decimal places from x without rounding\n\n- `sign(x)` - Returns the sign of x (-1, 0, or 1)\n\n- `clamp(x, min, max)` - Restricts x to be between min and max values\n\n### Exponential and Logarithmic Functions\n\n- `sqrt(x)` - Returns the square root of x\n\n- `cbrt(x)` - Returns the cube root of x\n\n- `ln(x)` - Returns the natural logarithm (base e) of x\n\n- `log(x)` - Returns the natural logarithm (base e) of x (alias of ln)\n\n- `log10(x)` - Returns the base-10 logarithm of x\n\n- `log2(x)` - Returns the base-2 logarithm of x\n\n### Trigonometric Functions\n\n- `sin(x)` - Returns the sine of x (x in radians)\n\n- `cos(x)` - Returns the cosine of x (x in radians)\n\n- `tan(x)` - Returns the tangent of x (x in radians)\n\n- `asin(x)` - Returns the arcsine of x in radians\n\n- `acos(x)` - Returns the arccosine of x in radians\n\n- `atan(x)` - Returns the arctangent of x in radians\n\n- `atan2(y, x)` - Returns the arctangent of the quotient of y and x in radians\n\n### Hyperbolic Functions\n\n- `sinh(x)` - Returns the hyperbolic sine of x\n\n- `cosh(x)` - Returns the hyperbolic cosine of x\n\n- `tanh(x)` - Returns the hyperbolic tangent of x\n\n- `asinh(x)` - Returns the inverse hyperbolic sine of x\n\n- `acosh(x)` - Returns the inverse hyperbolic cosine of x\n\n- `atanh(x)` - Returns the inverse hyperbolic tangent of x\n\n### String Functions\n\n- `concat(n1, n2, ..., n99)` - return all parameters into a string\n\n### Special Functions\n\n- `eval(expr)` - evaluate expression\n\n- `exist(o, key, type?)` - check if the key exists in the object, if type is not specified, it will be checked for all types, if type is specified, it will be checked for the specified type.\n\n- `if(a, b, c?)` - if `a` is true, then return `b`, otherwise return `c`\n\n- `noref(x)` - directly return x, because `ref` does not count the parentheses of a function, the parentheses wrapped in `noref` will not be included in the `ref`.\n\n- `max(n1, n2, ..., n99)` - maximum, note : `nX` can be number array.\n\n- `min(n1, n2, ..., n99)` - minimum, note : `nX` can be number array.\n\n- `sum(n1, n2, ..., n99)` - sum, note : `nX` can be number array.\n\n- `avg(n1, n2, ..., n99)` - average, note : `nX` can be number array.\n\n- `random(n)` - random number\n\n- `hypot(x1, x2, ..., xn)` - Returns the square root of the sum of squares of its arguments\n\n### Cast Functions\n\n- `string(expr)` - cast expr to string, note: `null` will be cast to an empty string, if `expr` is `undefined`, it will be as `null`\n\n- `number(expr)` - cast expr to number\n\n- `boolean(expr)` - cast expr to boolean\n\n## Custom Functions\n\nCustom functions can be used to extend the formula language. due to the formula supporting promise calculation, you can even provide UI related interactions in custom methods.\n\nCustom functions must include the following properties:\n```ts\ntype FormulaCustomFunctionItem = {\n  preExecute?: true,\n  arithmetic?: boolean,\n  argMin: number\n  argMax: number;\n  execute: (params: any[], dataSource: IFormulaDataSource, options: FormulaValueOptions, forArithmetic?: boolean) =\u003e any\n} | {\n  preExecute: false,\n  arithmetic?: boolean,\n  argMin: number\n  argMax: number;\n  execute: (params: FormulaValues, dataSource: IFormulaDataSource, options: FormulaValueOptions, forArithmetic?: boolean) =\u003e any\n}\n```\n\n| Property Name | Type | Default Value | Description |\n|---------------|------|---------------|-------------|\n| preExecute | boolean | true | Whether to preprocess parameters before execution. If `true`, all parameters will be executed to get results before executing `execute`. If set to `false`, the `params` passed to `execute` will be `FormulaValues` objects, and the user needs to call the parameter's execute method themselves (e.g., `params[0].execute(dataSource, options)`) to get the parameter values. |\n| arithmetic | boolean | false | The arithmetic nature of the custom function. If `true`, it indicates that the return value of this function will be a `number` type (or `Decimal` type). If this function is used as one of the parameters of a comparison operator, it will attempt to convert the other side's parameter to a number for comparison. If `false`, it indicates unknown. |\n| argMin | number | - | Minimum number of parameters. |\n| argMax | number | - | Maximum number of parameters. |\n| execute | (params, dataSource, options, forArithmetic) =\u003e any | - | Execution function, including parameters, data source, and options. Additionally, the `forArithmetic` parameter indicates whether the current function is being executed as one of the parameters in an arithmetic operation. |\n\nExample:\n\n```js\nimport formulaCalc from 'formula-calc';\n\nconst result = await formulaCalc('confirm(\"some prompt\", 1, 2) + 1', {\n  customFunctions: {\n    confirm: {\n      argMin: 3,\n      argMax: 3,\n      execute([prompt, a, b]) {\n        return new Promise((resolve) =\u003e {\n          // some UI interaction\n          setTimeout(() =\u003e {\n            resolve(a \u003e b ? a : b);\n          }, 1000);\n        });\n      }\n    }\n  }\n});\n```\n\n\n## License\n\n[MIT](./LICENSE)\n\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fgxlmyacc%2Fformula-calc","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fgxlmyacc%2Fformula-calc","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fgxlmyacc%2Fformula-calc/lists"}