JavaScript:十进制值 [英] JavaScript: Decimal Values
问题描述
我可以在JavaScript中使用什么十进制类型?它不受支持( 0.1 + 0.2!== 0.3
),我需要它来表示银行/金融应用程序中的确切值。请参阅 JavaScript的状态和未来 良好的阅读和JavaScript背后的脏细节以及它(缺乏)支持十进制算术。
What can I use as a decimal type in JavaScript? It's not supported (0.1 + 0.2 !== 0.3
), and I need it for representing exact values in a banking/financial application. See The State and Future of JavaScript for a good read and the dirty details behind JavaScript and it's (lack of) support for decimal arithmetic.
十进制,我的意思是:
- 无限范围和任意精度(如Java中的
BigDecimal
)或 - 有限的范围和精度,但适用于财务计算(如C#中的
十进制
)。
- infinite-range and arbitrary-precision (like
BigDecimal
in Java), or - limited range and precision, but suitable for financial calculations (like
decimal
in C#).
那么,使用十进制值的库或解决方案是什么?谢谢!
So, what library or solution exists for working with decimal values? Thanks!
推荐答案
通常建议 1 以整数代表分数处理货币: 2572
美分而不是 25.72
美元。这是为了避免您提到的浮点运算问题。幸运的是,浮点的整数运算是精确的,因此可以通过缩放来避免十进制表示错误。
It is often recommended1 to handle money as an integer representing the number of cents: 2572
cents instead of 25.72
dollars. This is to avoid the problems with floating-point arithmetic that you mention. Fortunately integer arithmetic in floating point is exact, so decimal representation errors can be avoided by scaling.
1 Douglas Crockford: JavaScript:好的部件:附录A - 可怕的部件(第105页)。
1Douglas Crockford: JavaScript: The Good Parts: Appendix A - Awful Parts (page 105).
这篇关于JavaScript:十进制值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!