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>
具体的函数请参阅官网
标签:console,log,0.1,浮点数,0.2,计算,JavaScripts,0.3,math From: https://www.cnblogs.com/AngryLeesin/p/18144192