前端精度計(jì)算Decimal.js基本用法與舉例詳解
一、Decimal.js 簡介
decimal.js 是一個用于任意精度算術(shù)運(yùn)算的 JavaScript 庫,它可以完美解決浮點(diǎn)數(shù)計(jì)算中的精度丟失問題。
官方API文檔:Decimal.js
特性:
任意精度計(jì)算:支持大數(shù)、小數(shù)的高精度運(yùn)算。
鏈?zhǔn)秸{(diào)用:簡潔的鏈?zhǔn)讲僮鞣绞健?/p>
支持所有常見運(yùn)算:加減乘除、取冪、平方根、取模等。
跨平臺:可以在瀏覽器和 Node.js 中使用。
安裝
在項(xiàng)目中使用 decimal.js 需要先安裝庫:
// 終端輸入命令 npm/cnpm/pnpm install decimal.js
二、Decimal.js 的基本用法
創(chuàng)建 Decimal 對象
可以通過構(gòu)造函數(shù)創(chuàng)建 Decimal 對象,支持多種格式的輸入。
import Decimal from 'decimal.js' // 創(chuàng)建 Decimal 對象,最好使用字符串,防止原生js數(shù)字過大自帶的精度問題,例如12345678987654321 const num1 = new Decimal(0.1);// 可以不要new關(guān)鍵字,兩種方法等同Decimal(0.1) const num2 = new Decimal('0.2'); const num3 = new Decimal(0.3); // 得到的結(jié)果是一個Decimal對象,需要使用Decimal對象的toString或者toNumber獲取正常數(shù)據(jù) console.log(num1.toString()); // 輸出 "0.1" console.log(num2.toString()); // 輸出 "0.2"
基本運(yùn)算
Decimal.js 支持常見的加、減、乘、除等操作。
const num1 = new Decimal(0.1); const num2 = new Decimal(0.2); console.log(num1.plus(num2).toString()); // 加法:0.3 console.log(num1.minus(num2).toString()); // 減法:-0.1 console.log(num1.times(num2).toString()); // 乘法:0.02 console.log(num1.div(num2).toString()); // 除法:0.5
鏈?zhǔn)秸{(diào)用
可以通過鏈?zhǔn)秸{(diào)用簡化復(fù)雜的計(jì)算邏輯。
const result = new Decimal(0.1).plus(0.2) .times(10) .div(3); console.log(result.toString()); // 輸出 "1"
比較大小
可以通過 Decimal 提供的比較方法來比較兩個數(shù)的大小。
const num1 = new Decimal(0.1); const num2 = new Decimal(0.2); console.log(num1.lessThan(num2)); // true console.log(num1.greaterThan(num2)); //false console.log(num1.equals(0.1)); // true
數(shù)學(xué)運(yùn)算
Decimal.js 還支持其他常見的數(shù)學(xué)操作,例如取冪、平方根等。
const num = new Decimal(2); console.log(num.pow(3).toString()); // 8 console.log(num.sqrt().toString()); // 1.4142135623730951
四舍五入與精度控制
Decimal.js 提供了方便的四舍五入和精度控制方法:
const num = new Decimal(1.23456789); console.log(num.toFixed(2)); // 1.23 console.log(num.toPrecision(4)); // 1.235 console.log(num.round().toString()); // 1
總結(jié)
到此這篇關(guān)于前端精度計(jì)算Decimal.js基本用法與舉例詳解的文章就介紹到這了,更多相關(guān)前端精度計(jì)算Decimal.js用法內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
JavaScript操作Oracle數(shù)據(jù)庫示例
這篇文章主要介紹了JavaScript操作Oracle數(shù)據(jù)庫示例,本文使用ActiveXObject實(shí)現(xiàn)訪問Oracle數(shù)據(jù)庫,需要的朋友可以參考下2015-03-03使用JavaScript實(shí)現(xiàn)類數(shù)組對象轉(zhuǎn)換為數(shù)組的方法
在?JavaScript?開發(fā)中,我們經(jīng)常會遇到"類數(shù)組對象"(array-like?objects),這些對象看起來像數(shù)組,有?length?屬性,也可以通過索引訪問元素,但它們不具備數(shù)組的方法,本文將詳細(xì)介紹如何將類數(shù)組對象轉(zhuǎn)換為真正的數(shù)組,需要的朋友可以參考下2025-04-04Javascript數(shù)據(jù)結(jié)構(gòu)與算法之列表詳解
這篇文章主要介紹了Javascript數(shù)據(jù)結(jié)構(gòu)與算法之列表詳解,本文講解了列表的抽象數(shù)據(jù)類型定義、如何實(shí)現(xiàn)列表類等內(nèi)容,需要的朋友可以參考下2015-03-03使用JavaScript實(shí)現(xiàn)小球按照貝塞爾曲線運(yùn)動
要在 JavaScript 中實(shí)現(xiàn)一個按照貝塞爾曲線運(yùn)動的小球,關(guān)鍵是要掌握貝塞爾公式的基本原理和實(shí)現(xiàn)方式,以及使用 JavaScript 處理動畫和物理運(yùn)算,感興趣的小伙伴跟著小編一起來看看吧2024-10-10多個jquery.datatable共存,checkbox全選異常的快速解決方法
這篇文章主要介紹了多個jquery.datatable共存,checkbox全選異常的快速解決方法。需要的朋友可以過來參考下,希望對大家有所幫助2013-12-12