JavaScript:a-calc解决前端精度问题

一、npm 搜索 a-calc 

a-calc是一个用于计算数学表达式的npm包。它可以处理基本的算术操作(如加法、减法、乘法和除法),并支持使用括号来控制运算顺序。除此之外,a-calc还提供了一些常用的数学函数,如平方根、求幂和取模运算。

使用a-calc非常简单。你只需要引入a-calc包,然后通过调用其提供的方法来进行计算。例如,你可以使用a-calc的add方法来计算两个数的和,使用multiply方法来计算两个数的乘积。

除了这些基本的操作,a-calc还提供了evaluate方法,可以用于计算复杂的数学表达式。你只需要将你的数学表达式作为参数传递给evaluate方法,它会返回计算结果。

总的来说,a-calc是一个方便易用的npm包,适用于在JavaScript项目中进行数学计算。无论是简单的算术运算还是复杂的数学表达式,a-calc都可以帮助你轻松地进行计算。

二、安装a-calc

npm i a-calc

三、使用a-calc

<template>
  <div class="container">
    <div>a-calc.js</div>
  </div>
</template>

<script setup lang="ts">
import {calc, fmt} from 'a-calc'
console.log('9calc', calc)
console.log('9fmt', fmt)
console.log(calc('0.1 + 0.2')) // 加法
console.log(calc('0.1 + 0.2 * 0.3 / 0.4 * (0.5 + 0.6)')) // 更复杂的计算
console.log(calc('-2e2 + 3e+2')) // 科学记数法中的计算

let a = 0.000001
let b = 888.789
console.log(calc("a + b", {a,b})) // 0.000001 + 888.789 = 888.789001

console.log(calc("a * (b + c) % d + 7.123", [
    {a: 1, b: 2},
    {c: 3, d: 4}
])) // 8.123

// A bit more complex
console.log(calc("1 + o.a / arr[0].d",{
    o: { a: 2 },
    arr: [{ d: 8 }]
})) // 1.25

console.log(calc("a + b - c",[
    {a: 1},
    {b: 2, c: 3}
]))

console.log(calc("1 + 2%", {_unit: true})) // 3%

console.log(calc("1.123$$$ + 2.88% | + =6", {_unit: true})) // +4.003000$$$

console.log(calc("0.1 + 0.2 | =2")) // 0.30
console.log(calc("0.11111 + 0.11111 | <=4")) // 0.2222
console.log(calc("0.11 + 0.11 | <=4")) // 0.22
console.log(calc("0.1 + 0.2 | >= 5")) // 0.30000
console.log(calc("0.0000001+ 0.0000001 | >= 5")) // 0.0000002

// Preserve positive and negative signs
console.log(calc("1 + 1 | +")) // +2

// Thousandth place
console.log(calc("10000000 + 100000000 | ,")) // 110,000,000

// Fraction
console.log(calc("0.025 + 0.2 | /")) // 9/40

// Percentage
console.log(calc("1 + 1 | %")) // 200%

// Scientific notation, note that this e can also be capitalized
console.log(calc("1 + 1 | !e")) // 2e+0

// Simultaneously specify decimals and thousandth place while preserving the positive and negative signs
console.log(calc("10000000 + 100000000 | +,=10")) // +110,000,000.0000000000

console.log(calc("0.1 | =2")) // 0.10
console.log(fmt("0.1 | =2")) // 0.10
// calc has the function of fmt, but fmt has better semantics
console.log(fmt("1000000 | ,")) // 1,000,000


</script>

<style scoped lang="less">

</style>

四、欢迎交流指正

参考链接

a-calc - npm

a-calc前端精度问题的终极解决方案,计算不准不方便就用它! - 知乎

  • 9
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值