a-calc 1.3.8 → 1.3.10-dev.20240306

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,349 +1,352 @@
1
- # a-calc
2
- A convenient library for accurate calculation and formatting of numbers, which can solve the following problems:
3
-
4
- * Size: uncompressed size 56KB. Gzip compression size 18KB
5
- * Make the number calculation of javascript accurate
6
- * Other third-party libraries have poor coding experience and inconvenient formatting
7
- * Scientific notation of possible output of numerical calculation
8
- * Format digits, output digits in thousandths, format digits directly into percentages, keep signs of digits, output fractions directly, etc.
9
- * Calculation or formatting of numbers with units, e.g.: `0.1% + 2%`
10
- * Calculation in scientific notation, for example: `-2e3 + 6`
11
- * Support four rounding rules: rounding to the end, rounding to one, rounding to five, rounding to six (a more accurate method)
12
-
13
- > Supported operators : + - * / % **
14
-
15
- **Language:** English | [简体中文](https://github.com/Autumn-one/a-calc-old/blob/main/README_ZH.md)
16
-
17
- ## Installation
18
-
19
- ```
20
- npm install a-calc
21
- ```
22
-
23
- ## Import
24
-
25
- **commonjs**
26
-
27
- ```js
28
- const {calc, fmt} = require("a-calc")
29
- // or
30
- const {calc, fmt} = require("a-calc/cjs") // Note that this is written to explicitly specify the use of the cjs version which makes sense, some packaging tools will do a conversion of the syntax, directly write a-calc does not work (nuxt.js is), then replace it with a-calc/cjs try
31
- ```
32
-
33
- **es module**
34
-
35
- ```js
36
- import {calc, fmt} from "a-calc"
37
- // or
38
- const {calc, fmt} from "a-calc/es"
39
- ```
40
-
41
- **browser**
42
-
43
- ```html
44
- <script src="node_modules/a-calc/browser/index.js"></script>
45
- <script>
46
- const {calc, fmt} = a_calc
47
- </script>
48
- ```
49
-
50
- ## Usage
51
-
52
- ```js
53
- calc("0.1 + 0.2") // 0.3
54
-
55
- // A little more complicated calculation
56
- calc("0.1 + 0.2 * 0.3 / 0.4 * (0.5 + 0.6)") // 0.265
57
-
58
- // Calculation of scientific notation
59
- calc("-2e2 + 3e+2") // 100
60
- ```
61
-
62
- ## About Spaces
63
-
64
- Spaces are non-essential in the absence of ambiguity, and can even correctly parse the following writing `calc("-2e+2+3e+2")` which is difficult for the human eye to parse, but this is too low clarity, please do your best to write clearer code instead of shit! <span style="color: red;">Always include spaces in your formula, which is more beautiful and clear, just like the example I wrote!!!</span>
65
-
66
- By the way, an ambiguous equation `calc("50%%2", {_unit: true})` This ambiguity obviously occurs when calculating with units, since the parser doesn't know whether your units are `%` or `%%` so you have to use spaces to give a clear meaning, the correct way to write it would be `calc("50% % 2", {_unit: true}) `
67
-
68
- In short, always add space!
69
-
70
- ## Fill variables and calculate (important)
71
-
72
- **The calculated value is accurate and there is no scientific counting method**
73
-
74
- ```js
75
- let a = 0.000001
76
- let b = 888.789
77
- calc("a + b", {a,b}) // 0.000001 + 888.789 = 888.789001
78
-
79
- calc("a * (b + c) % d + 7.123", [
80
- {a: 1, b: 2},
81
- {c: 3, d: 4}
82
- ]) // 8.123
83
-
84
- // A little more complicated
85
- calc("1 + o.a / arr[0].d",{
86
- o: { a: 2 },
87
- arr: [{ d: 8 }]
88
- }) // 1.25
89
-
90
- calc("a + b - c",[
91
- {a: 1},
92
- {b: 2, c: 3}
93
- ])
94
- ```
95
-
96
- ## Calculation with unit
97
-
98
- > The reality is not always ideal, maybe we have to calculate two percentage numbers, fortunately a-calc supports these operations now, but please note that the units will be taken from the first number carrying the unit, and the subsequent units will be ignored
99
-
100
- ```js
101
- // It is important to note that this is required and not enabled by default, because calculations with units do some extra work, which is faster than calculations with numbers alone
102
- calc("1 + 2%", {_unit: true}) // 3%
103
-
104
- calc("1.123$$$ + 2.88% | + =6", {_unit: true}) // +4.003000$$$
105
- ```
106
-
107
- After `1.0.6`, calculations with units can have more parameters, `_unit` can take values like `boolean | "on" | "off" | "auto" | "space"` The parameters look like a lot, but they are similar to the previous usage, `true "on" "auto"` has the same effect, it means that it automatically recognizes the number after the The biggest difference is that the `"space"` value means that only spaces are used as unit separators. For example, if your units happen to be `+-`, which would be recognized as an operator in normal mode, you can use the `"space"` mode, but then spaces are required, and you would write it like this: `calc ("2+- * 3")` The final result is: `6+-`
108
-
109
-
110
-
111
- In practice, you may want the final result not to carry units automatically. In versions after `1.3.6`, you can remove the units from the result with the formatting parameter `!u`, or `!n` can output the number directly.
112
-
113
- ## Calculate and format
114
-
115
- Formatting supports the following features: limit decimal places, Keep Plus and minus signs, percentage output, scientific notation output, and kilobyte output, and they can be combined, but there are individual combinations that are not valid, try This yourself. There are too many combinations to list one by one.
116
-
117
- **Formatted list:**
118
-
119
- - `>|>=|<|<=|=Numeric` means restrict the number of decimal places, for example: `<=2` the number of decimal places is less than or equal to 2 `>3` the number of decimal places must be greater than 3, this is equivalent to `>=4`
120
- - `,` The output is a string of digits in the thousandths
121
- - `/` Output as fraction
122
- - `+` Output positive numbers with `+` sign
123
- - `%` Output a percentage number that can be used in combination with restricted decimals
124
- - `!e` The output is scientific notation and e can be capitalized
125
- - `!n` The output is a number rather than a numeric string, n can be capitalized, and after version 1.3.6 this has the highest priority, any other formatting parameter cannot affect this parameter.
126
- - `!u` Remove units from results
127
-
128
- ```js
129
- // Operational decimal places
130
- calc("0.1 + 0.2 | =2") // 0.30
131
- calc("0.11111 + 0.11111 | <=4") // 0.2222
132
- calc("0.11 + 0.11 | <=4") // 0.22
133
- calc("0.1 + 0.2 | >= 5") // 0.30000
134
- calc("0.0000001+ 0.0000001 | >= 5") // 0.0000002
135
-
136
- // Keep the sign
137
- calc("1 + 1 | +") // +2
138
-
139
- // thousands
140
- calc("10000000 + 100000000 | ,") // 110,000,000
141
-
142
- // Fraction
143
- calc("0.025 + 0.2 | /") // 9/40
144
-
145
- // Percentage
146
- calc("1 + 1 | %") // 200%
147
-
148
- // Scientific notation, notice that this e can also be capitalized
149
- calc("1 + 1 | !e") // 2e+0
150
-
151
- // Specifies both the decimal and the thousandth digits and leaves the sign plus or minus
152
- calc("10000000 + 100000000 | +,=10") // +110,000,000.0000000000
153
- ```
154
-
155
- ## Four rounding rules
156
-
157
- The rounding rule is added to the part of the format string, whose symbols are respectively:
158
-
159
- - `~-` Tail off, default rounding rule
160
- - `~+` Enter One
161
- - `~5` Rounding
162
- - `~6` This rounding rule is more accurate than rounding. The rule is different when the last digit of the rounding rule is 5. It looks at the position after 5, and if the last digit is not 0, it goes to 1, if the following number is 0, then you will see if the number before 5 is even, if it is not enter, not enter
163
-
164
- ```js
165
- calc("0.11 + 0.22 | =1 ~+") // 0.4 Keep one digit and enter one
166
- calc("0.55 | =1 ~5") // 0.6
167
- calc("0.65 | =1 ~6") // 0.6
168
- ```
169
-
170
- This newly added rounding rule seems to make the formatted part longer, but this is not the case. Generally, the rounding rule of an item is fixed, so the formatting of the rounding rule part should be encapsulated in the default formatting parameters. In actual use, there is no need to write this part at all. Refer to the "Default Format" description below
171
-
172
- ## Format only
173
-
174
- ```js
175
- calc("0.1 | =2") // 0.10
176
- fmt("0.1 | =2") // 0.10
177
- // Calc has the functionality of fmt, but fmt has better semantics
178
-
179
- fmt("1000000 | ,") // 1,000,000
180
- ```
181
-
182
- ## Configure version number printing and library update detection
183
-
184
- You can turn the console on or off to print the version number of the current library, or you can turn the console on or off to prompt if there is a new version update.
185
-
186
- ```typescript
187
- import { calc_util } from "a-calc"
188
- calc_util.print_version(); // Print version in console
189
- calc_util.check_update(); // Enable the update detection function, if there are updates will be alerted in the console
190
- ```
191
-
192
- ## Advanced skills
193
-
194
- **Error Handling**
195
-
196
- > Usually using calc directly requires the input formula to be completely correct. By default a-calc will not help you deal with the error of the formula. This can be filtered by yourself, but we may not want to do this in the project, so we need an extra advanced API to silently capture and give an appropriate return value when the input formula is wrong
197
-
198
- ```js
199
- calc("1 + 2sd + d",{
200
- _fill_data: {d: 3}, // From here, the data source object is assigned to _fill_data, which can also be an array of objects. When fetching data, it is successively searched from the array items, and the first one is immediately stopped
201
- _error: "-", // Returns - as an alternative value if the equation is wrong
202
- })
203
-
204
- // The above writing can be simplified
205
- calc("1 + 2sd + d", {
206
- d: 8,
207
- _error: "-"
208
- }) // This simplification is simply for convenience
209
- ```
210
-
211
- **Default formatting**
212
-
213
- > Default formatting can be used to optimize the development experience in real projects
214
-
215
- ```js
216
- calc("111111 + 11111 | ,",{_fmt: "=2"}) // 122,222.00 Obviously , and =2 are combined, and the formatted string in the expression has higher priority
217
- ```
218
-
219
- ## How to re-encapsulate in the project?
220
-
221
- The core ` calc ` function may not be extremely convenient in a real project, so ` a-calc ` provides a built-in secondary encapsulation function ` calc_wrap ` after version `1.2.10`, which is essentially an extension of ` calc `, so it has all the functions of the former, just more flexible writing and powerful type derivation.
222
-
223
- Note that this may not be the only correct way to encapsulate. I just provide this function. There is no dogma here. You should be flexible in your own scenarios.
224
-
225
- I suggest that if you decide to introduce ` calc_wrap ` into your project, you can rename it to ` calc ` so that you can write a few fewer characters. The following shows some flexible writing and powerful type derivation.
226
-
227
- ```typescript
228
- // Note that calc_wrap is renamed calc here, because if you need to use the calc_wrap function, you basically don't need the core calc function, so if you have this idle name, you should use it
229
- import { calc_wrap as calc } from "a-calc";
230
-
231
- const state = {
232
- a: 1,
233
- b: 2,
234
- c: 3
235
- };
236
-
237
- // When the parameter passed in is a formula without variable name, the calculation result will be returned directly
238
- calc( "(1 + 2) * 3" ); // Return type: string
239
-
240
- // When the incoming argument is a formula that is suspected to contain a variable name and there is no second data source argument, it returns a function waiting for the incoming data source. Yes, this function is done by statically typed derivation
241
- calc( "(a + b) * c" ); // Return type: ( data: any ) => string
242
- calc( "(a + b) * c" )( state ); // Return type: string
243
-
244
- // Maybe you want to inject state first and then enter an expression, which is also ok
245
- calc( state ); // Return type: ( expr: string | number ) => string
246
- calc( state )( "(a + b) * c" ); // Return type: string
247
-
248
- // The original usage is naturally supported
249
- calc( "a + b + c", state ); // Return type: string
250
-
251
- // You can still mix the configuration with the data source, which is very convenient
252
- calc( "a + b + c" )( { ...state, _error: 0 } ); // Return type: string | 0
253
- ```
254
-
255
- ### Disrecommended writing
256
-
257
- `a-calc` can be written using template strings, but I've found in practice that the readability of this writing is terrible, and it's not recommended unless you really have a valid enough reason to use template strings.
258
-
259
- ```typescript
260
- calc(`${a} + ${b}`) // This writing style is not recommended
261
- calc("a + b", {a,b}) // Recommended writing style because it is clearer
262
- ```
263
-
264
-
265
-
266
- ## Version change
267
-
268
- * 1.3.8 Solve the packaging failure caused by the upgrade of vite5.x (Feedback from 武建鹏)
269
- * 1.3.6
270
- - The `!n` formatting parameter is adjusted to the highest priority and any other formatting parameter cannot affect it.
271
- - New `!u` formatting parameter to remove the unit part of the result
272
- - Type Hint Enhancement
273
- * 1.3.4
274
- - Resolve the bug of rounding and rounding to six formatting errors(bug provider: nanarino)
275
- * 1.3.0
276
- - Disruptive changes: Adjust how the version number printing function and the detection update function are called
277
- - Perfect type hint
278
- - Add more unit tests
279
- * 1.2.30
280
- - Previous versions would have controlled the print version number by default, now it is configurable and turned off by default
281
- - Provides the function of detecting updates, after opening if there is a new version of this will give a prompt in the console
282
- * 1.2.10
283
- - Remove the vue integration example, the library itself is not bound to a front-end framework, to avoid misunderstanding, remove the corresponding integration code.
284
- - Add `calc_wrap` function, which is the second wrapping of the core function `calc` and can be used directly.
285
- * 1.2.6
286
- - Adjust the vue3 integration code, because the vue3 component instances differ between the development environment and the production environment, the production environment cannot get the state, but the development environment can.
287
- * 1.2.0
288
- - Very minor breaking update, the former `-e` and `-n` become `!e` and `!n` respectively
289
- - Document update
290
- * 1.1.0
291
- - Very minor loop-breaking update, the previous `\e` scientific notation output is now `-e`, the rest is unchanged
292
- - Added `-n` output number type
293
- - Support `<` and `>` symbols for decimal place restrictions
294
- - Fixed several rounding formatting issues
295
- - Increased the number of unit tests to 107
296
- * 1.0.25
297
- - Documentation update to simplify writing a-calc integration to vue3
298
- * 1.0.23
299
- - Updated documentation to rewrite the recommended way to integrate a-calc into vue3
300
- * 1.0.22
301
- - Optimize fractional rounding logic
302
- * 1.0.21
303
- - Improve export type definition
304
- * 1.0.19
305
- - Fix the problem that _error may not catch errors when it is an empty string.
306
- * 1.0.14
307
- - Fix ** operator priority error.
308
- - Fix for `<=` formatting that may have extra zeros not removed.
309
- * 1.0.12
310
- - Document add library volume description
311
- - Fix the problem that the _error parameter is still abnormal when the expression is null, and add the corresponding unit test.
312
- * 1.0.10
313
- - Update documentation
314
- * 1.0.6
315
- * Destructive change: all exposed small humps are now snake naming, e.g. `_fillData` is now `_fill_data`, because the snake naming is clearer.
316
- * The internal code has been greatly simplified and the parser has been almost completely rewritten to bring a more stable experience
317
- * The original design was that the calc function had all the functionality of fmt, but while versions prior to 1.0.6 conformed to this design, calc and fmt were implemented separately, and now fmt is just an alias for calc.
318
- * Support for the new operator **
319
- * Support for new formatting characters % Can output numbers as percentages
320
- * Support for the new formatting character `\e`, which can format numbers into scientific notation
321
- * Fix a problem that may cause a dead loop when formatting an illegal string
322
- * Fix the problem that 1/0 is Infinity.
323
- * Add several unit tests
324
- * More detailed type hints
325
- * Update documentation to add sample code for vue3 integration
326
- * 0.0.80
327
- * Bring 4 types of rounding rules, which are: rounding to the end, rounding to one, rounding to five, rounding to six
328
- * More boundary case detection
329
- * fmt allows not passing in formatted strings, a feature that allows you to use fmt to remove extra zeros after the decimal point
330
- * 0.0.79
331
- * Update documentation
332
- * 0.0.78
333
- * Support for scientific notation calculations
334
- * Full unit tests
335
- * More boundary case detection
336
- * 0.0.72
337
- * Support for writing single values with units, e.g. `calc("$1", {_unit: true})` or `fmt("$1 | =2",{_unit: true})`
338
- * Additional documentation
339
-
340
- ## Attention
341
-
342
- - Do not wrap parentheses around a single number
343
-
344
- ## Question submission
345
-
346
- (If you encounter any problems, please be the first to send me feedback email, 718879459@qq.com for bugs I will be the first to fix him)
347
-
348
-
349
-
1
+ # a-calc
2
+ A library for performing four operations on numeric strings originating from actual business can solve the following problems:
3
+
4
+ * Size: Uncompressed volume is 56KB. Gzip compressed volume is 18KB.
5
+ * The precision problem of JS numerical computation.
6
+ * The coding experience with other third-party libraries is poor and formatting is not convenient enough.
7
+ * Number calculations may output in scientific notation
8
+ * Numeric formatting, thousand-separator output, direct formatting into percentage, retaining positive or negative signs, direct fraction output, etc.
9
+ * Calculation or formatting of numbers with units, e.g. `0.1% + 2%`
10
+ * Calculation using scientific notation, e.g. `-2e3 + 6`
11
+ * Supports four kinds of rounding rules: truncating, incrementing, rounding, and rounding to even (a more precise method).
12
+
13
+ > 支持的运算符 : + - * / % **
14
+
15
+ **Language:** English | [简体中文](https://github.com/Autumn-one/a-calc-old/blob/main/README_ZH.md)
16
+
17
+ ## Installation
18
+
19
+ ```
20
+ npm install a-calc
21
+ ```
22
+
23
+ ## Import
24
+
25
+ **commonjs**
26
+
27
+ ```js
28
+ const {calc, fmt} = require("a-calc")
29
+ // or
30
+ const {calc, fmt} = require("a-calc/cjs") // Note that this syntax specifically uses the cjs version. Some bundlers will transform the syntax. If writing a-calc directly doesn't work, try changing it to a-calc/cjs.
31
+ ```
32
+
33
+ **es module**
34
+
35
+ ```js
36
+ import {calc, fmt} from "a-calc"
37
+ // or
38
+ const {calc, fmt} from "a-calc/es"
39
+ ```
40
+
41
+ **browser**
42
+
43
+ ```html
44
+ <script src="node_modules/a-calc/browser/index.js"></script>
45
+ <script>
46
+ const {calc, fmt} = a_calc
47
+ </script>
48
+ ```
49
+
50
+ ## Four arithmetic operations (supports scientific notation)
51
+
52
+ ```js
53
+ calc("0.1 + 0.2") // 0.3
54
+
55
+ // More complex calculation
56
+ calc("0.1 + 0.2 * 0.3 / 0.4 * (0.5 + 0.6)") // 0.265
57
+
58
+ // Calculation in scientific notation
59
+ calc("-2e2 + 3e+2") // 100
60
+ ```
61
+
62
+ ## About the space
63
+
64
+ Spaces are not necessary in cases where there is no ambiguity, and it can even correctly parse the hard-to-read-by-human formula `calc("-2e+2+3e+2")`. However, this makes the clarity too low. Please try your best to write clearer code instead of shit! <span style="color: red;">Always include spaces in your calculation, which makes it more beautiful and clear, just like the examples I wrote!!!</span>
65
+
66
+ By the way, here's an ambiguous formula `calc("50%%2", {_unit: true})`. This ambiguity obviously occurs in calculations with units. Since the parser doesn't know if your unit is `%` or `%%`, you should use a space to give a clear meaning. The correct way to write is `calc("50% % 2", {_unit: true})`.
67
+
68
+ In short, always add spaces!
69
+
70
+ ## Fill in variables and calculate (important)
71
+
72
+ **The calculated value is precise and scientific notation will not appear.**
73
+
74
+ ```js
75
+ let a = 0.000001
76
+ let b = 888.789
77
+ calc("a + b", {a,b}) // 0.000001 + 888.789 = 888.789001
78
+
79
+ calc("a * (b + c) % d + 7.123", [
80
+ {a: 1, b: 2},
81
+ {c: 3, d: 4}
82
+ ]) // 8.123
83
+
84
+ // A bit more complex
85
+ calc("1 + o.a / arr[0].d",{
86
+ o: { a: 2 },
87
+ arr: [{ d: 8 }]
88
+ }) // 1.25
89
+
90
+ calc("a + b - c",[
91
+ {a: 1},
92
+ {b: 2, c: 3}
93
+ ])
94
+ ```
95
+
96
+ ## Calculation with units
97
+
98
+ > The actual situation is not always ideal, maybe we have to calculate two percentage numbers. Fortunately, a-calc now supports these operations, but please note that the unit will be taken from the first number carrying a unit, and the units later will be ignored.
99
+
100
+ ```js
101
+ // Please note that _unit is required and not enabled by default. This is because calculations with units will perform some additional operations, and in contrast, pure numerical calculations are faster.
102
+ calc("1 + 2%", {_unit: true}) // 3%
103
+
104
+ calc("1.123$$$ + 2.88% | + =6", {_unit: true}) // +4.003000$$$
105
+ ```
106
+
107
+ After version 1.0.6, calculations with units can have more parameters. The value of `_unit` can be `boolean | "on" | "off" | "auto" | "space"`. The parameters seem to be a lot but actually are similar to the previous usage. The effects of `true "on" "auto"` are the same, which means to automatically recognize the unit after the number. `false "off"` means to turn off the unit calculation. The biggest difference is the "space" value, which only treats the space as a unit separator. For example, if your unit happens to be +-, it will be recognized as an operator in normal mode, so you can use the "space" mode. But in this case, the space is necessary. You should write like this: `calc("2+- * 3")`. The final result is: `6+-`.
108
+
109
+ In actual development, you may hope that the final result does not automatically carry units. In versions after 1.3.6, you can remove units from the result through the formatting parameter `!u`, or you can directly output the number with `!n`.
110
+
111
+ ## Calculate and format
112
+
113
+ Formatting supports the following functions: limiting the number of decimal places, preserving positive and negative signs, outputting as a percentage, outputting in scientific notation, outputting, and they can be combined. However, there are some situations where combinations do not work. You can try it yourself, there are too many combination situations, and I won't list them all.
114
+
115
+ **Formatting list:**
116
+
117
+ - `>or>=or<or<=or=number` means to limit the number of decimal places, for example: `<=2` means the number of decimal places should be less than or equal to 2 `>3` means the number of decimal places must be greater than 3, this is equivalent to `>=4`
118
+ - `,` Output as a thousandth place numeric string
119
+ - `/` Output as a fraction
120
+ - `+` The output positive numbers are marked with a `+` sign
121
+ - `%` Output percentage numbers, which can be combined with the option to limit the number of decimals.
122
+ - `!e` Output in scientific notation, e can be capitalized
123
+ - `!n` Output as a number, not a numeric string, n can be capitalized. After version 1.3.6, this has the highest priority, and any other formatting parameters cannot affect this parameter.
124
+ - `!u` Remove units from the result
125
+
126
+ ```js
127
+ // Operate the decimal places
128
+ calc("0.1 + 0.2 | =2") // 0.30
129
+ calc("0.11111 + 0.11111 | <=4") // 0.2222
130
+ calc("0.11 + 0.11 | <=4") // 0.22
131
+ calc("0.1 + 0.2 | >= 5") // 0.30000
132
+ calc("0.0000001+ 0.0000001 | >= 5") // 0.0000002
133
+
134
+ // Preserve positive and negative signs
135
+ calc("1 + 1 | +") // +2
136
+
137
+ // Thousandth place
138
+ calc("10000000 + 100000000 | ,") // 110,000,000
139
+
140
+ // Fraction
141
+ calc("0.025 + 0.2 | /") // 9/40
142
+
143
+ // Percentage
144
+ calc("1 + 1 | %") // 200%
145
+
146
+ // Scientific notation, note that this e can also be capitalized
147
+ calc("1 + 1 | !e") // 2e+0
148
+
149
+ // Simultaneously specify decimals and thousandth place while preserving the positive and negative signs
150
+ calc("10000000 + 100000000 | +,=10") // +110,000,000.0000000000
151
+ ```
152
+
153
+ ## Four kinds of rounding rules
154
+
155
+ The rounding rules are added to the part of the formatting string, and their symbols are:
156
+
157
+ - `~-` Truncation, the default rounding rule
158
+ - `~+` Increment
159
+ - `~5` Rounding
160
+ - `~6` Round to Even, this rounding rule is more accurate than the normal rounding. The rule is different when the number after the rounding is 5. It will check the position after 5. If the number after 5 is not 0, it will increment. If the number after 5 is 0, it will check whether the number before 5 is even or not. If it is even, it will not increment. If it is not even, it will increment.
161
+
162
+ ```js
163
+ calc("0.11 + 0.22 | =1 ~+") // 0.4 Keep one place and increment it
164
+ calc("0.55 | =1 ~5") // 0.6
165
+ calc("0.65 | =1 ~6") // 0.6
166
+ ```
167
+
168
+ This newly added rounding rule seems to make the formatting part longer, but the actual situation is not like this. Generally, the rounding rule of a project is fixed, so the formatting part of the rounding rule should be encapsulated in the default formatting parameters. When it is actually used, there is no need to write this part of the content at all. Refer to the following `default formatting` instructions.
169
+
170
+ ## Only format
171
+
172
+ ```js
173
+ calc("0.1 | =2") // 0.10
174
+ fmt("0.1 | =2") // 0.10
175
+ // calc has the function of fmt, but fmt has better semantics
176
+
177
+ fmt("1000000 | ,") // 1,000,000
178
+ ```
179
+
180
+ ## Configure version number printing and library update detection
181
+
182
+ You can turn on or off the console printing of the current library version number, and you can also turn on or off console prompts for whether there is a new version update.
183
+
184
+ ```typescript
185
+ import { calc_util } from "a-calc"
186
+ calc_util.print_version(); // Print the version in the console
187
+ calc_util.check_update(); // Enable the update detection function. If there are updates, it will remind you in the console.
188
+ ```
189
+
190
+ ## Advanced techniques
191
+
192
+ **Error handling**
193
+
194
+ > Typically, using calc directly requires that the input calculation formula is completely correct, and by default a-calc will not help you handle errors in the formula. This can be filtered out by oneself, but in the project, we might not want to do this, so we need an additional advanced API to silently capture and give an appropriate return value when the input formula is incorrect.
195
+
196
+ ```js
197
+ calc("1 + 2sd + d",{
198
+ _fill_data: {d: 3}, // From here, the data source object needs to be assigned to _fill_data. This object can also be an array of objects. At this time, when obtaining data, it is searched item by item from the array, and it stops immediately when the first one is found.
199
+ _error: "-", // When the calculation formula is wrong, it returns - as an alternative value.
200
+ })
201
+
202
+ // The above writing can be simplified a bit.
203
+ calc("1 + 2sd + d", {
204
+ d: 8,
205
+ _error: "-"
206
+ }) // This simplification is purely for convenience.
207
+ ```
208
+
209
+ **Default formatting**
210
+
211
+ > In actual projects, you can optimize the development experience through default formatting.
212
+
213
+ ```js
214
+ calc("111111 + 11111 | ,",{_fmt: "=2"}) // 122,222.00 Obviously , and =2 are combined, and the format string in the expression has a higher priority.
215
+ ```
216
+
217
+ ## How to encapsulate for the second time in the project?
218
+
219
+ In actual projects, the core calc function may not be extremely convenient. Therefore, `a-calc` provides a built-in function `calc_wrap` for secondary encapsulation after version 1.2.10. Essentially, it is an extension of calc, so it has all the former's capabilities but with more flexible writing methods and powerful type inference.
220
+
221
+ Please note that this may not be the only correct way to encapsulate. I just provided this feature. There is no dogma here. You should adapt flexibly to your own scenarios.
222
+
223
+ I suggest that if you decide to bring calc_wrap into the project, you can rename it as calc to save a few characters. The following will show some flexible writing methods and powerful type inference.
224
+
225
+ ```typescript
226
+ // Note that here we rename calc_wrap as calc, because if you need to use the calc_wrap function, the core calc function is basically not needed, so if this good name is idle, it should be used.
227
+ import { calc_wrap as calc } from "a-calc";
228
+
229
+ const state = {
230
+ a: 1,
231
+ b: 2,
232
+ c: 3
233
+ };
234
+
235
+ // When the passed parameter is a calculation formula without a variable name, it will directly return the calculation result.
236
+ calc( "(1 + 2) * 3" ); // Return type: string
237
+
238
+ // When the passed parameter is a suspected calculation formula containing a variable name and there is no second data source parameter, a function waiting for a data source to be passed will be returned. Yes, this function is achieved through static type deduction.
239
+ calc( "(a + b) * c" ); // Return type: ( data: any ) => string
240
+ calc( "(a + b) * c" )( state ); // Return type: string
241
+
242
+ // Maybe you want to inject the state first and then enter the expression. This is also possible.
243
+ calc( state ); // Return type: ( expr: string | number ) => string
244
+ calc( state )( "(a + b) * c" ); // Return type: string
245
+
246
+ // The original usage is naturally also supported.
247
+ calc( "a + b + c", state ); // Return type: string
248
+
249
+ // You can still mix configuration and data sources together, which is very convenient.
250
+ calc( "a + b + c" )( { ...state, _error: 0 } ); // Return type: string | 0
251
+ ```
252
+
253
+ ### Not recommended writing
254
+
255
+ `a-calc` can use the template string syntax, but I found that the readability of this writing method is very poor in practice. Unless you really have a sufficiently reasonable reason, it is not recommended to use the template string syntax.
256
+
257
+ ```typescript
258
+ calc(`${a} + ${b}`) // This way of writing is not recommended.
259
+ calc("a + b", {a,b}) // Recommended writing, because it is clearer.
260
+ ```
261
+
262
+
263
+
264
+ ## Version changes
265
+
266
+ * 1.3.9 Solved the problem of failed rounding due to the part of the injection variable in formatting being 0 (Problem reporter: MangMax)
267
+ * 1.3.8 Solved the packaging failure problem caused by the upgrade of vite5.x (Problem reporter: 武建鹏)
268
+ * 1.3.6
269
+ - The priority of the `!n` formatting parameter has been adjusted to the highest, and no other formatting parameters can affect it.
270
+ - Added `!u` formatting parameter, which can remove the unit part from the result.
271
+ - Type hint enhancement
272
+ * 1.3.4
273
+ - Fixed the bug of rounding error between rounding off and rounding to nearest even number (bug provider: nanarino)
274
+ * 1.3.0
275
+ - BREAKING CHANGE: Adjust the invocation method of printing version and checking update function
276
+ - Refine Type Hints
277
+ - Add more unit tests.
278
+ * 1.2.30
279
+ - The previous version printed version numbers by default, now it is configurable and disabled by default
280
+ - It provides an update detection function. Once enabled, the console will give a hint if there is a new version.
281
+ * 1.2.10
282
+ - Remove the Vue integration example. The library itself is not bound to any specific frontend framework, in order to avoid misunderstandings, delete the corresponding integration code.
283
+ - Add the functionality of `calc_wrap`, which is a secondary wrapper for the core function `calc` and can be used directly.
284
+ * 1.2.6
285
+ - Adjust the integrated code of vue3. Since the component instances of vue3 are different in the development environment and the production environment, the production environment cannot obtain the state, but the development environment can.
286
+ * 1.2.0
287
+ - A minor disruptive update, where the previous `-e` and `-n` have been changed to `!e` and `!n`, respectively.
288
+ - Document Update
289
+ * 1.1.0
290
+ - Small breaking change, the previous `\e` scientific counting output is now `-e`, others did not change
291
+ - Added `-n` to output the number type
292
+ - The limitation on decimal places is supported by the `<` and `>` symbols.
293
+ - Fixed several rounding formatting issues.
294
+ - The unit tests have increased to 107.
295
+ * 1.0.25
296
+ - Update the document to simplify the integration of a-calc into Vue3.
297
+ * 1.0.23
298
+ - Update the document and rewrite the recommended way to integrate a-calc into Vue3.
299
+ * 1.0.22
300
+ - Optimize decimal rounding logic.
301
+ * 1.0.21
302
+ - Refine the exported type definitions.
303
+ * 1.0.19
304
+ - Fix the issue where errors may not be captured when _error is an empty string.
305
+ * 1.0.14
306
+ - Fix the issue of `**` operator precedence error.
307
+ - Fix the issue of extra zeros not being removed when formatting with `<=`.
308
+ * 1.0.12
309
+ - Document adding library volume description
310
+ - Fix the issue where adding the _error parameter when the expression is empty still causes an error, and include corresponding unit tests.
311
+ * 1.0.10
312
+ - Update document
313
+ * 1.0.6
314
+ * Destructive change: all exposed camelCase naming has been converted to snake_case, for example, `_fillData` is now `_fill_data`, as snake_case naming is clearer.
315
+ * The internal code has been greatly simplified, the parser has been almost completely rewritten, resulting in a more stable user experience.
316
+ * The original design was for the calc function to have all the functionalities of fmt. However, in versions prior to 1.0.6, although they adhered to this design, calc and fmt were implemented separately. Now fmt is simply an alias for calc.
317
+ * Support the new operator **.
318
+ * Support for the new formatting character % allows numbers to be output as percentages.
319
+ * Support for the new formatting character `\e`, which can format numbers in scientific notation.
320
+ - Fixed the issue where illegal formatting strings could cause an infinite loop.
321
+ - Resolved the problem of 1/0 resulting in Infinity.
322
+ - Added several unit tests.
323
+ - More detailed type hints.
324
+ - Updated documentation, added example code for integrating with Vue3.
325
+ * 0.0.80
326
+ * Introducing four rounding rules: truncation, rounding up to the nearest integer, round half up, and round half down.
327
+ - Enhanced detection of more boundary cases.
328
+ - The fmt function allows omitting the format string. This feature enables you to use fmt to remove trailing zeros after the decimal point.
329
+ * 0.0.79
330
+ * Update document
331
+ * 0.0.78
332
+ * Support calculation in scientific notation
333
+ * Comprehensive unit testing
334
+ * Detection of more boundary cases
335
+ * 0.0.72
336
+ * Support writing single numerical values with units, for example `calc("1 yuan", {_unit: true})` or `fmt("1 yuan | =2",{_unit: true})`
337
+ * Supplement documentation
338
+
339
+ ## Attention
340
+
341
+ - Do not enclose individual numbers in parentheses.
342
+
343
+ ## Video tutorial
344
+
345
+ To be determined
346
+
347
+ ## Issue submission
348
+
349
+ When providing feedback, please include error examples and as much information about the issue as possible. Avoid submitting overly abstract or general statements as feedback! A new version addressing the problem will typically be released within one working day.
350
+
351
+
352
+