JavaScript:十进制值

编程入门 行业动态 更新时间:2024-10-26 14:39:06
本文介绍了JavaScript:十进制值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我可以在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:十进制值

    本文发布于:2023-10-09 10:31:05,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1475492.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:JavaScript   十进制值

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!