BigDecimal 在 JavaScript 中的应用
本文将讨论 JavaScript 中 BigDecimal
的用法。
在 JavaScript 中使用 BigDecimal
在研究 BigDecimal
如何在 JavaScript 中工作之前,你必须了解 BigDecimal
。BigDecimal
由具有 32 位整数刻度的未缩放任意精度整数值组成。
如果小数位数为零或正数,则为小数点右侧的位数。如果整数为负数,则将未缩放的值乘以 10 的负数次方。
BigDecimal
使用二进制浮点整数的十进制表示来确定相等和哈希码。这与使用精确形式的 Long 和 Double 数字之间的转换产生不同的结果。
请注意,在运行代码之前,你必须安装 BigDecimal
的 npm
包。
将以下代码另存为 js
扩展文件。
let bDecimal = require('bigdecimal');
let num = new bDecimal.BigInteger('123456abcdefghijklmn7890', 25);
console.log('num is ' + num);
let newD = new bDecimal.BigDecimal(num);
let k = new bDecimal.BigDecimal('4567890.12345612345678901234567890123');
console.log('newD * k = ' + newD.multiply(k));
let two = new bDecimal.BigDecimal('2');
console.log('Average = ' + newD.add(k).divide(two));
你可以看到不同的方法,例如 multiply()
、add()
、divide()
。add()
方法将一个 BigDecimal
对象值添加到另一个 newD
是 BigDecimal
对象的位置,newD
添加到 k
。
multiply()
方法将一个 BigDecimal
对象值乘以另一个,而 divide()
方法将一个 BigDecimal
值除以另一个值。
将 Double 或 Float 转换为 BigDecimal
时,必须小心,因为 Double 和 Float 的二进制小数表示不会简单地转换为十进制表示。
输出:
BigDecimal
非常适合金融数据算术或任何超过 JavaScript 整数(IEEE-754 浮点)类型的数据。新的 ECMAScript 标准中不包含十进制。
相关文章
Do you understand JavaScript closures?
发布时间:2025/02/21 浏览次数:108 分类:JavaScript
-
The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.
Do you know about the hidden traps in variables in JavaScript?
发布时间:2025/02/21 浏览次数:178 分类:JavaScript
-
Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av
How much do you know about the Prototype Chain?
发布时间:2025/02/21 浏览次数:150 分类:JavaScript
-
The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start
用 jQuery 检查复选框是否被选中
发布时间:2024/03/24 浏览次数:102 分类:JavaScript
-
在本教程中学习 jQuery 检查复选框是否被选中的所有很酷的方法。我们展示了使用直接 DOM 操作、提取 JavaScript 属性的 jQuery 方法以及使用 jQuery 选择器的不同方法。你还将找到许多有用的
jQuery 中的 Window.onload 与 $(document).ready
发布时间:2024/03/24 浏览次数:180 分类:JavaScript
-
本教程演示了如何在 jQuery 中使用 Window.onload 和 $(document).ready 事件。