JavaScript:十进制值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3454965/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JavaScript: Decimal Values
提问by Mr. X
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 JavaScriptfor a good read and the dirty details behind JavaScript and it's (lack of) support for decimal arithmetic.
我可以在 JavaScript 中使用什么作为十进制类型?它不受支持 ( 0.1 + 0.2 !== 0.3),我需要它来表示银行/金融应用程序中的确切值。请参阅The State and Future of JavaScript以获得良好的阅读和 JavaScript 背后的肮脏细节以及它(缺乏)对十进制算术的支持。
By "decimal", I mean either:
通过“十进制”,我的意思是:
- infinite-range and arbitrary-precision (like
BigDecimalin Java), or - limited range and precision, but suitable for financial calculations (like
decimalin C#).
- 无限范围和任意精度(如
BigDecimal在 Java 中),或 - 范围和精度有限,但适用于财务计算(如
decimal在 C# 中)。
So, what library or solution exists for working with decimal values? Thanks!
那么,有哪些库或解决方案可用于处理十进制值?谢谢!
回答by Daniel Vassallo
It is often recommended1to handle money as an integer representing the number of cents: 2572cents instead of 25.72dollars. 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处理为表示美分数的整数:2572美分而不是25.72美元。这是为了避免您提到的浮点运算问题。幸运的是,浮点中的整数运算是精确的,因此可以通过缩放来避免十进制表示错误。
1Douglas Crockford: JavaScript: The Good Parts: Appendix A - Awful Parts (page 105).
1Douglas Crockford:JavaScript:好的部分:附录 A - 糟糕的部分(第 105 页)。
回答by Razor Storm
Javascript does have floating point support. But anyway, for financial records, the simplest implementation would simply be storing your values in standard integers. You may either declare an integer to represent the amount in cents, or two integers one for dollars and one for cents.
Javascript 确实有浮点支持。但无论如何,对于财务记录,最简单的实现就是将您的值存储在标准整数中。您可以声明一个整数来表示以美分为单位的金额,也可以声明两个整数,一个表示美元,一个表示美分。
So $18.57 would become 1857cents in the first technique or 18 dollars and 57 cents in the second.
因此,第一种技术中的 18.57 美元将变为 1857 美分,或者第二种技术中的 18 美元和 57 美分。
This has the added advantage of being completely accurate, as integers are stored purely as unique binary representation, there would be no such thing as rounding errors.
这具有完全准确的额外优势,因为整数纯粹以唯一的二进制表示形式存储,因此不会有舍入错误之类的事情。
回答by pedroteixeira
It seems the following library implements decimal in js (node and browser): https://npmjs.org/package/jsdecimal
似乎以下库在 js(节点和浏览器)中实现了十进制:https: //npmjs.org/package/jsdecimal

