a-calc
A convenient library for accurate calculation and formatting of numbers, which can solve the following problems:
- Size: uncompressed size 35-43KB. Gzip compression size 13-15KB
- Make the number calculation of javascript accurate
- Other third-party libraries have poor coding experience and inconvenient formatting
- Scientific notation of possible output of numerical calculation
- Format digits, output digits in thousandths, format digits directly into percentages, keep signs of digits, output fractions directly, etc.
- Calculation or formatting of numbers with units, e.g.:
0.1% + 2%
- Calculation in scientific notation, for example:
-2e3 + 6
- Support four rounding rules: rounding to the end, rounding to one, rounding to five, rounding to six (a more accurate method)
Supported operators : + - * / % **
Language: 英文 | 简体中文
Installation
npm install a-calc
Import
commonjs
const {calc, fmt} = require("a-calc")
const {calc, fmt} = require("a-calc/cjs")
es module
import {calc, fmt} from "a-calc"
const {calc, fmt} from "a-calc/es"
browser
<script src="node_modules/a-calc/browser/index.js"></script>
<script>
const {calc, fmt} = a_calc
</script>
Usage
calc("0.1 + 0.2")
calc("0.1 + 0.2 * 0.3 / 0.4 * (0.5 + 0.6)")
calc("-2e2 + 3e+2")
About Spaces
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! Always include spaces in your formula, which is more beautiful and clear, just like the example I wrote!!!
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})
In short, always add space!
Fill variables and calculate (important)
The calculated value is accurate and there is no scientific counting method
let a = 0.000001
let b = 888.789
calc("a + b", {a,b})
calc("a * (b + c) % d + 7.123", [
{a: 1, b: 2},
{c: 3, d: 4}
])
calc("1 + o.a / arr[0].d",{
o: { a: 2 },
arr: [{ d: 8 }]
})
calc("a + b - c",[
{a: 1},
{b: 2, c: 3}
])
Calculation with unit
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
calc("1 + 2%", {_unit: true})
calc("1.123$$$ + 2.88% | + =6", {_unit: true})
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+-
Calculate and format
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.
Formatted list:
>|>=|<|<=|=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
,
The output is a string of digits in the thousandths/
Output as fraction+
Output positive numbers with +
sign%
Output a percentage number that can be used in combination with restricted decimals!e
The output is scientific notation and e can be capitalized!n
The output is a number, not a numeric string, and N can be uppercase, but if you set percentiles, fractions, or percentages, disk formatting and so on, this option does not take effect
calc("0.1 + 0.2 | =2")
calc("0.11111 + 0.11111 | <=4")
calc("0.11 + 0.11 | <=4")
calc("0.1 + 0.2 | >= 5")
calc("0.0000001+ 0.0000001 | >= 5")
calc("1 + 1 | +")
calc("10000000 + 100000000 | ,")
calc("0.025 + 0.2 | /")
calc("1 + 1 | %")
calc("1 + 1 | !e")
calc("10000000 + 100000000 | +,=10")
Four rounding rules
The rounding rule is added to the part of the format string, whose symbols are respectively:
~-
Tail off, default rounding rule~+
Enter One~5
Rounding~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
calc("0.11 + 0.22 | =1 ~+")
calc("0.55 | =1 ~5")
calc("0.65 | =1 ~6")
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
Format only
calc("0.1 | =2")
fmt("0.1 | =2")
fmt("1000000 | ,")
Advanced skills
Error Handling
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
calc("1 + 2sd + d",{
_fill_data: {d: 3},
_error: "-",
})
calc("1 + 2sd + d", {
d: 8,
_error: "-"
})
Default formatting
Default formatting can be used to optimize the development experience in real projects
calc("111111 + 11111 | ,",{_fmt: "=2"})
Use gestures in projects(vue3)
It is not good to write a huge second parameter in the project, so you should find a way to fix it. The following is just a demonstration in the VUE project
Integration into vue3 templates
You can use unplugin-auto-import
to automatically integrate it into the template, see the documentation of the corresponding plugin, or use the app.config.globalProperties
binding of vue if you want to integrate it manually
import { calc } from "a-calc";
import type {CalcConfig} from "a-calc";
import get from "lodash/get"
function calc_wrap ( expr: string, obj?: CalcConfig )
{
const instance: any = getCurrentInstance();
const data_arr = [ get( instance, "setupState" ), get( instance, "data" ) ];
const options = { _error: "-" };
if ( obj !== undefined )
{
data_arr.unshift( obj );
Object.keys( obj ).forEach( key => key.startsWith( "_" ) && ( options[key] = obj[key] ) );
}
return calc( expr, {
_fill_data: data_arr,
...options
} );
}
const fmt = calc;
export {
calc_wrap as calc,
fmt
};
Integrated into script setup
Still using the above functions, you can still use the unplugin-auto-import
plugin to automatically import them, and the actual development experience is like calc
is a global function without import.
Of course if you don't use this plugin to import automatically then you need to import it every time you write.
Usage in templates
calc in the template has access to all the states defined in setup, so it can be written directly. Sometimes the state state comes from the scope slot, which is passed in as an additional second parameter.
<style>
</style>
<template>
<div class="demo-autumn">
{{ calc( "a + (b + state.c) * state.d" ) }}
</div>
</template>
<script lang="ts" setup>
const a = 1;
const b = 2;
const state = reactive( {
c: 3,
d: 4
} );
</script>
Usage in script setup
This should be noted that using calc
directly in the setup top-level scope does not access the setup internal state, but it can be accessed directly during the life cycle.
<script lang="ts" setup>
const a = 1;
const b = 2;
const state = reactive( {
c: 3,
d: 4
} );
console.log( calc( "c + d", state ) ); // This is the setup top-level scope, so the internal state cannot be accessed, and data needs to be injected through the second parameter
onMounted( () =>
{
console.log( calc( "a + b + state.c + state.d" ) ); // Life cycle functions can be performed without injection
} );
</script>
Disrecommended writing
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.
calc(`${a} + ${b}`)
calc("a + b", {a,b})
Version change
- 1.2.0
- Very minor breaking update, the former
-e
and -n
become !e
and !n
respectively - Document update
- 1.1.0
- Very minor loop-breaking update, the previous
\e
scientific notation output is now -e
, the rest is unchanged - Added
-n
output number type - Support
<
and >
symbols for decimal place restrictions - Fixed several rounding formatting issues
- Increased the number of unit tests to 107
- 1.0.25
- Documentation update to simplify writing a-calc integration to vue3
- 1.0.23
- Updated documentation to rewrite the recommended way to integrate a-calc into vue3
- 1.0.22
- Optimize fractional rounding logic
- 1.0.21
- Improve export type definition
- 1.0.19
- Fix the problem that _error may not catch errors when it is an empty string.
- 1.0.14
- Fix ** operator priority error.
- Fix for
<=
formatting that may have extra zeros not removed.
- 1.0.12
- Document add library volume description
- Fix the problem that the _error parameter is still abnormal when the expression is null, and add the corresponding unit test.
- 1.0.10
- 1.0.6
- Destructive change: all exposed small humps are now snake naming, e.g.
_fillData
is now _fill_data
, because the snake naming is clearer. - The internal code has been greatly simplified and the parser has been almost completely rewritten to bring a more stable experience
- 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.
- Support for the new operator **
- Support for new formatting characters % Can output numbers as percentages
- Support for the new formatting character
\e
, which can format numbers into scientific notation - Fix a problem that may cause a dead loop when formatting an illegal string
- Fix the problem that 1/0 is Infinity.
- Add several unit tests
- More detailed type hints
- Update documentation to add sample code for vue3 integration
- 0.0.80
- Bring 4 types of rounding rules, which are: rounding to the end, rounding to one, rounding to five, rounding to six
- More boundary case detection
- fmt allows not passing in formatted strings, a feature that allows you to use fmt to remove extra zeros after the decimal point
- 0.0.79
- 0.0.78
- Support for scientific notation calculations
- Full unit tests
- More boundary case detection
- 0.0.72
- Support for writing single values with units, e.g.
calc("$1", {_unit: true})
or fmt("$1 | =2",{_unit: true})
- Additional documentation
Attention
- Do not wrap parentheses around a single number
Question submission
(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)