前端vue項目如何使用Decimal.js做加減乘除求余運算
1 vue項目安裝Decimal
npm install decimal.js
2 注意
運算結果是Decimal對象,需要使用.toNumber()轉(zhuǎn)為數(shù)字
3 加 add
const Decimal = require('decimal.js')
const num1 = Decimal("5");
const num2 = Decimal("3");
const remainder = num1.add(num2);
4 減 sub
const Decimal = require('decimal.js')
const num1 = Decimal("5");
const num2 = Decimal("3");
const remainder = num1.sub(num2);
5 乘 mul
const Decimal = require('decimal.js')
const num1 = Decimal("5");
const num2 = Decimal("3");
const remainder = num1.mul(num2);
6 除 div
const Decimal = require('decimal.js')
const num1 = Decimal("5");
const num2 = Decimal("3");
const remainder = num1.div(num2);
7 求余 modulo
const Decimal = require('decimal.js')
const num1 = Decimal("5");
const num2 = Decimal("3");
const remainder = num1.modulo(num2);附:vue 使用decimal.js 解決小數(shù)相加合計精確度丟失問題
- 安裝依賴 decimal.js
- npm install --save decimal.js
- 封裝
- 在utils文件夾下創(chuàng)建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>總結
到此這篇關于前端vue項目如何使用Decimal.js做加減乘除求余運算的文章就介紹到這了,更多相關vue Decimal.js做加減乘除求余運算內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
vue實現(xiàn)網(wǎng)絡圖片瀑布流 + 下拉刷新 + 上拉加載更多(步驟詳解)
這篇文章主要介紹了vue實現(xiàn)網(wǎng)絡圖片瀑布流 + 下拉刷新 + 上拉加載更多,本文分步驟通過實例代碼給大家介紹的非常詳細,具有一定的參考借鑒價值,需要的朋友可以參考下2020-01-01
vue3數(shù)據(jù)可視化實現(xiàn)數(shù)字滾動特效代碼
這篇文章主要介紹了vue3數(shù)據(jù)可視化實現(xiàn)數(shù)字滾動特效,實現(xiàn)思路是使用Vue.component定義公共組件,使用window.requestAnimationFrame(首選,次選setTimeout)來循環(huán)數(shù)字動畫,詳細代碼跟隨小編一起看看吧2022-09-09
vue 自定義提示框(Toast)組件的實現(xiàn)代碼
這篇文章主要介紹了vue 自定義提示框(Toast)組件的實現(xiàn)代碼,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-08-08
vue 實現(xiàn)click同時傳入事件對象和自定義參數(shù)
這篇文章主要介紹了vue 實現(xiàn)click同時傳入事件對象和自定義參數(shù),具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-01-01
使用form-create動態(tài)生成vue自定義組件和嵌套表單組件
這篇文章主要介紹了使用form-create動態(tài)生成vue自定義組件和嵌套表單組件,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2019-01-01
vue3+element?plus中利用el-menu如何實現(xiàn)路由跳轉(zhuǎn)
這篇文章主要給大家介紹了關于vue3+element?plus中利用el-menu如何實現(xiàn)路由跳轉(zhuǎn)的相關資料,在Vue?Router中我們可以使用el-menu組件來實現(xiàn)菜單導航,通過點擊菜單項來跳轉(zhuǎn)到不同的路由頁面,需要的朋友可以參考下2023-12-12

