- 安装依赖 decimal.js
- npm install --save decimal.js
- 封装
| import { Decimal } from 'decimal.js' |
| export function add (x, y) { |
| if (!x) { |
| x = 0 |
| } |
| if (!y) { |
| y = 0 |
| } |
| const xx = new Decimal(x) |
| const yy = new Decimal(y) |
| return xx.plus(yy).toNumber() |
| } |
| |
| export function sub (x, y) { |
| if (!x) { |
| x = 0 |
| } |
| if (!y) { |
| y = 0 |
| } |
| const xx = new Decimal(x) |
| const yy = new Decimal(y) |
| return xx.sub(yy).toNumber() |
| } |
| |
| export function div (x, y) { |
| if (!x) { |
| x = 0 |
| } |
| if (!y) { |
| return 0 |
| } |
| const xx = new Decimal(x) |
| const yy = new Decimal(y) |
| return xx.div(yy).toNumber() |
| } |
| |
| export function mul (x, y) { |
| if (!x) { |
| x = 0 |
| } |
| if (!y) { |
| y = 0 |
| } |
| const xx = new Decimal(x) |
| const yy = new Decimal(y) |
| return xx.mul(yy).toNumber() |
| } |
复制
<script>
import {add} from "@/utils/decimal"
export default {
methods:{
handlePlus() {
add(10.5,4.877)
}
}
}
</script>
复制