前端vue項目如何使用Decimal.js做加減乘除求余運算
更新時間:2024年05月28日 08:59:23 作者:H_HX126
decimal.js是使用的二進(jìn)制來計算的,可以更好地實現(xiàn)格化式數(shù)學(xué)運算,對數(shù)字進(jìn)行高精度處理,使用decimal類型處理數(shù)據(jù)可以保證數(shù)據(jù)計算更為精確,這篇文章主要給大家介紹了關(guān)于前端vue項目如何使用Decimal.js做加減乘除求余運算的相關(guān)資料,需要的朋友可以參考下
1 vue項目安裝Decimal
npm install decimal.js
2 注意
運算結(jié)果是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>
總結(jié)
到此這篇關(guān)于前端vue項目如何使用Decimal.js做加減乘除求余運算的文章就介紹到這了,更多相關(guān)vue Decimal.js做加減乘除求余運算內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
您可能感興趣的文章:
相關(guān)文章
vue實現(xiàn)點擊按鈕“查看詳情”彈窗展示詳情列表操作
這篇文章主要介紹了vue實現(xiàn)點擊按鈕“查看詳情”彈窗展示詳情列表操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-09-09Vue中scrollIntoView()方法詳解與實際運用舉例
這篇文章主要給大家介紹了關(guān)于Vue中scrollIntoView()方法詳解與實際運用舉例的相關(guān)資料,該scrollIntoView()方法將調(diào)用它的元素滾動到瀏覽器窗口的可見區(qū)域,需要的朋友可以參考下2023-12-12Vue+Openlayers實現(xiàn)實時坐標(biāo)點展示
這篇文章主要為大家詳細(xì)介紹了Vue+Openlayers實現(xiàn)實時坐標(biāo)點展示,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-03-03