我可以在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.
十进制,我的意思是:
那么,使用十进制值的库或解决方案是什么?谢谢!
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:十进制值
发布评论