JavaScript中的精确财务计算。有什么问题? [英] Precise Financial Calculation in JavaScript. What Are the Gotchas?

查看:170
本文介绍了JavaScript中的精确财务计算。有什么问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为了创建跨平台代码,我想用JavaScript开发一个简单的财务应用程序。所需的计算涉及复合利息和相对较长的十进制数。我想知道在使用JavaScript进行这种类型的数学时要避免哪些错误 - 如果有可能的话!

In the interest of creating cross-platform code, I'd like to develop a simple financial application in JavaScript. The calculations required involve compound interest and relatively long decimal numbers. I'd like to know what mistakes to avoid when using JavaScript to do this type of math—if it is possible at all!

推荐答案

您应该将小数值缩放100,并以整分美分表示所有货币值。这是为了避免浮点逻辑和算术问题。 JavaScript中没有十进制数据类型 - 唯一的数字数据类型是浮点数。因此,通常建议以 2550 美分而不是 25.50 美元来处理金钱。

You should probably scale your decimal values by 100, and represent all the monetary values in whole cents. This is to avoid problems with floating-point logic and arithmetic. There is no decimal data type in JavaScript - the only numeric data type is floating-point. Therefore it is generally recommended to handle money as 2550 cents instead of 25.50 dollars.

在JavaScript中考虑:

Consider that in JavaScript:

var result = 1.0 + 2.0;     // (result === 3.0) returns true

但是:

var result = 0.1 + 0.2;     // (result === 0.3) returns false

表达式 0.1 + 0.2 === 0.3 返回 false ,但幸运的是浮点数中的整数运算是精确的,因此可以通过缩放 1 。

The expression 0.1 + 0.2 === 0.3 returns false, but fortunately integer arithmetic in floating-point is exact, so decimal representation errors can be avoided by scaling1.

请注意,虽然实数集合是无限的,但只有有限数量(准确地说是18,437,736,874,454,810,627)可以完全由JavaScript浮点格式。因此,其他数字的表示将是实际数字 2 的近似值。

Note that while the set of real numbers is infinite, only a finite number of them (18,437,736,874,454,810,627 to be exact) can be represented exactly by the JavaScript floating-point format. Therefore the representation of the other numbers will be an approximation of the actual number2.

1 Douglas Crockford: JavaScript:好的部分:附录A - 可怕的零件(第105页)

2 David Flanagan: JavaScript:权威指南,第四版:3.1.3浮点文字(第31页)

1 Douglas Crockford: JavaScript: The Good Parts: Appendix A - Awful Parts (page 105).
2 David Flanagan: JavaScript: The Definitive Guide, Fourth Edition: 3.1.3 Floating-Point Literals (page 31).

这篇关于JavaScript中的精确财务计算。有什么问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆