JS数学运算精度问题
最近项目上JS做加减乘除这类的运算出现了精度不匹配的问题:
例如:
- 0.1+0.2
- ->0.30000000000000004
- 0.3-0.2
- ->0.09999999999999998
- 0.3*2
- ->0.6
- 0.3*0.2
- 0.06
- 0.3/3
- ->0.09999999999999999
Mathjs这个JS库可以解决这类问题:官网链接
以下是详细的步骤:
-
终端执行
npm install mathjs
-
然后引入所有的库
import * as math from "mathjs";
-
组件代码如下:
<template>
<article class="article">
<h3 class="title">{{ title }}</h3>
</article>
</template>
<script>
import * as math from "mathjs";
export default {
data() {
return {
title: "Hello World",
};
},
methods: {
oldNumberTest() {
console.log("===oldNumberTest===");
console.log("0.1+0.2=",0.1+0.2);
console.log("0.89-0.2=",0.89-0.2);
console.log("0.1*0.2=",0.1*0.2);
console.log("0.3/3=",0.3/3);
},
mathNumber(){
console.log("===mathNumber===");
let sum=this.convert(math.add(math.fraction(0.1), math.fraction(0.2)))
console.log("math.add(0.1,0.2)=",sum);
},
convert(value) {
return(math.format(value, { fraction: "decimal" }));
},
},
created() {
this.oldNumberTest();
this.mathNumber();
},
};
</script>
<style lang="stylus" scoped>
.article
.title
border-bottom: solid 3px rgba(red, .2)
</style>
具体的函数请参阅官网
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!