前端技术:vue2.0
这个插件的大小只有1.14kb, 非常轻量化可以用来处理小数数值加减乘除的精度问题
0.1+0.2=? 正常逻辑下 ,结果应该是0.3,我们来看一下控制台的结果输出!
结果却是:0.30000000000000004
这就是小数的计算精度问题, 在小数计算中我们会经常遇到类似的问题,非常的影响计算结果
下面就要来介绍这款插件了。
安装
npm安装:
npm install --save currency.js
yarn安装:
yarn add currency.js
全局挂载方法
在main.js文件中引入全局挂载方法,后面我们在使用过程中就不需要再次手动引入啦!
// 货币的计算方法
import currency from 'currency.js'
// 全局方法挂载
Vue.prototype.currency = currency
使用它:
<template>
<div id="app">
<p>{{result}}</p>
<button @click="add">添加(0.11)</button>
</div>
</template>
<script>
export default {
name: 'App',
components: {
},
data: () => {
return {
result: 20.12,
}
},
created() {
},
methods: {
add() {
//正常添加 使用请注释掉一个区分效果
this.result += 0.11
//使用currency添加
this.result = this.currency(this.result).add(0.11)
}
}
}
</script>
<style>
p {
padding: 20px;
margin: 20px;
background-color: #ccc;
border-radius: 5px;
}
</style>
正常添加:会出现精度问题
使用currency添加
上面div标签中没有用到this是因为this可以省略不写,在js中 this指向vue实例,因为已经在vue实例上挂在了currency方法,所以可以直接通过this调用它。