decimal.js
是一个 JavaScript 库,用于处理任意精度的十进制数。它非常适合处理金融数据和其他需要高精度的场景。它提供了丰富的API来执行各种数学运算,包括加法、减法、乘法、除法和幂运算等。此外,decimal.js
还支持设置精度和舍入模式,以满足不同的计算需求。
介绍 decimal.js地址
安装 decimal.js
使用案例 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 import { Decimal } from "decimal.js" ; let x = new Decimal (123.4567 );let y = new Decimal ("123456.7e-3" );let z = new Decimal (x);let bool = x.equals (y) && y.equals (z) && x.equals (z); console .log (bool); var a = new Decimal ("0.1" );var b = new Decimal ("0.2" );console .log (a.plus (b).toString ()); const num1 = new Decimal ("0.12365" );const num2 = new Decimal (100 ); const sum = num1.plus (num2); const difference = num1.minus (num2); const product = num1.times (num2); const quotient = num1.dividedBy (num2); console .log (sum.toString ()); console .log (difference.toString ()); console .log (product.toString ()); console .log (quotient.toString ()); Decimal .config ({ precision : 20 , rounding : Decimal .ROUND_HALF_UP , }); const divisionResult = new Decimal ("1" ).dividedBy (new Decimal ("3" ));console .log (divisionResult.toString ()); const absValue = num1.abs (); const isGreaterThan = num1.greaterThan (num2); const power = num1.pow (2 ); console .log (absValue);console .log (isGreaterThan); console .log (power);const numAsString = num1.toString (); const numAsNumber = num1.toNumber (); console .log (numAsString); console .log (numAsNumber);