首页 > web前端 > js教程 > JavaScript 中的财务精确度:处理金钱而不损失一分钱

JavaScript 中的财务精确度:处理金钱而不损失一分钱

WBOY
发布: 2024-08-10 06:45:02
原创
881 人浏览过

Financial Precision in JavaScript: Handle Money Without Losing a Cent

在快节奏的金融世界中,精确性就是一切。最好避免因舍入/精度错误而造成百万美元的损失。

说到金钱,请考虑数据类型

本文的出发点是认识到金钱并不是你可以用来数篮子里苹果的平均基本数字。当您尝试将 10 欧元乘以 10 美元时,您会得到什么?很难啊……你有没有在旧夹克的口袋里发现过神奇的 1.546 美元?是的,我知道,这也是不可能的。这些愚蠢的例子是为了说明这样一个事实:金钱有其自己的特定规则,不能仅用简单的数字来建模。我向你保证,我不是第一个意识到这一点的人(也许你比我早意识到这一点)。 2002年,程序员Martin Fowler在《企业应用架构模式》中提出了一种用特定属性和操作数规则来表示货币的方法。对他来说,货币数据类型所需的两个最小可行属性是:

amount
currency
登录后复制

这个非常基本的表示将是我们构建一个简单但强大的货币模型的起点。

金额,如何表示

金额绝对是一个特定的数字:它具有固定的精度(同样,你的口袋里不可能有 4.376 美元)。您需要选择一种能够帮助您尊重此约束的表示方式。

一种朴素的方法,原生数字 JavaScript 数据类型

剧透警告,如果你不想看到几美分(如果不是美元)消失在浮点数表示的黑暗世界中,这绝对不是一个好主意。

代价高昂的精度误差

如果您有一些 JavaScript 编码经验,您就会知道,即使是最简单的计算也可能会导致您一开始意想不到的精度错误。强调这种现象的最明显和最著名的例子是:

0.1 + 0.2 !== 0.3 // true
0.1 + 0.2 // 0.30000000000000004
登录后复制

如果这个例子不能完全说服你,我建议你看看这篇文章,它深入探讨了使用 JavaScript 原生数字类型时可能遇到的所有有问题的计算结果......

结果中的这种微小差异可能对您来说似乎无害(幅度约为 10^-16),但是在关键的金融应用程序中,此类错误可能会迅速级联。考虑在数千个账户之间转移资金,其中每笔交易都涉及类似的计算。这些轻微的误差加起来,在你意识到之前,你的财务报表就已经减少了数千美元。老实说,我们都同意,在金钱方面,错误是不允许的:无论是在法律上还是与客户建立信任关系。

为什么会出现这样的错误?

在我的一个项目中遇到此问题时,我问自己的第一个问题是为什么?我发现问题的根源不是 JavaScript,这些不精确性也会影响其他现代编程语言(Java、C、Python……)。

// In C
#include <stdio.h>

int main() {
    double a = 0.1;
    double b = 0.2;
    double sum = a + b;
    if (sum == 0.3) {
        printf("Equal\n");
    } else {
        printf("Not Equal\n"); // This block is executed
    }
    return 0;
}

// > Not equal
登录后复制
// In Java
public class doublePrecision {
    public static void main(String[] args) {

        double total = 0;
        total += 5.6;
        total += 5.8;
        System.out.println(total);
    }
}

// > 11.399999999999
登录后复制

事实上,根本原因在于这些语言用来表示浮点数的标准:IEEE 754 标准指定的双(或单)精度浮点格式。

IEEE 754 标准:位表示的故事

在Javascript中,原生类型数字对应的是双精度浮点数,这意味着一个数字用64位编码,分为三部分:

  • 1 位符号
  • 11 位指数
  • 52 位尾数(或分数),范围从 0 到 1

Financial Precision in JavaScript: Handle Money Without Losing a Cent

Financial Precision in JavaScript: Handle Money Without Losing a Cent

然后,您需要使用以下公式将您的位表示形式转换为十进制值:

Financial Precision in JavaScript: Handle Money Without Losing a Cent

双精度浮点数表示的示例,近似为 1/3 :

0 01111111101 0101010101010101010101010101010101010101010101010101

= (-1)^0 x (1 + 2^-2 + 2^-4 + 2^-6 + ... + 2^-50 + 2^-52) x 2^(1021-1023)
= 0.333333333333333314829616256247390992939472198486328125
~ 1/3
登录后复制

This format allows us to represent a vast range of values, but it can't represent every possible number with absolute precision (just between 0 and 1 you can find an infinity of numbers…). Many numbers cannot be represented exactly in binary form. To loop on the first example, that's the issue with 0.1 and 0.2. Double-point floating representation gives us an approximation of these value, so when you add these two imprecise representations, the result is also not exact.

A possible solution: Arbitrary Decimal Arithmetic

Now that you are fully convinced that handling money amounts with native JavaScript number type is a bad idea (at least I hope you begin to have doubts about it), the 1Billion$ question is how should you proceed ? A solution could be to make use of some of the powerful fixed-precision arithmetic packages available in JavaScript. For example Decimal.js (which is used by the popular ORM Prisma to represent its Decimal datatype) or Big.js.

These packages provide you with special datatypes that allow you to perform calculations with getting rid of precision errors we explained above.

// Example using Decimal.js
const Decimal = require('decimal.js');
const a = new Decimal('0.1');
const b = new Decimal('0.2');
const result = a.plus(b);

console.log(result.toString()); // Output: '0.3'
登录后复制

This approach provides you with another advantage, it drastically extends the maximum value that can be represented, which can become pretty handy when you are dealing with cryptocurrencies for example.
Even if it is really robust, that it not the one I prefer to choose to implement in my web applications. I find it easier and clearer to apply Stripe strategy to only deal with integer values.

Learn from Masters : Stripe, a No-Floating Points Strategy

We, at Theodo Fintech, value pragmatism! We love to take inspiration from the most succeeding companies in the industry. Stripe, the well-known billions$ company specialized in payment services, made the choice to handle money amounts without floating numbers but with integers. To do that, they use the smallest unit of the currency to represent a monetary amount.

// 10 USD are represented by
{
 "amount": 1000,
 "currency": "USD"
}
登录后复制

Currency Minimal Units… Are Not Consistent!

I guess that many of you already know this: all currencies don't have the smallest unit of the same magnitude. Most of them are "two-decimal" currencies (EUR, USD, GBP) which means that their smallest unit is 1/100th of the currency. However, some are "three-decimal" currencies (KWD) or even "zero-decimal" currencies (JPY). (You can find more information about it by following the ISO4217 standard). To handle these disparities, you should integrate to your money data representation the multiplicative factor to convert an amount represented in the smallest unit into the corresponding currency.

Financial Precision in JavaScript: Handle Money Without Losing a Cent

I Chose a Way to Represent Money Amount… OK, But Now, How Do I Round Them?

I guess you already figured it out, you can either work with native number , third party arbitrary-precision packages or integers, calculations can (and will) lead you to floating-point results that you will need to round to your monetary finite precision. As a quick example is never to much, let's say that you handle integer values and contracted a loan of 16k$ with a really precise interest rate of 8.5413% (ouch…). You then need to refund 16k$ plus an additional amount of

1600000 * 0.085413 // amount in cents
//Output in cents: 136660.8
登录后复制

The crux is to properly handle the rounding process of money amounts after calculations. Most of the time, you end up having to choose between three different kinds of rounding:

  • Classic rounding: Round to the closest value and if halfway between two values, round up
  • Banker rounding: Round to the closest value and if halfway between two values, round down if the number is even, and round up if the number is odd (this gives you numerical stability when you have to perform lots of rounding)
  • Custom rounding: based on particular legislation for the currency you use and the use case you are handling

When it comes to roundings, there is not really any "magic sauce": you need to arbitrate depending on your situation. I recommend you always check legislation when you deal with a new currency and a new rounding use case (conversion, money split, interest rates for credits, …). You better follow regulations right away to avoid further troubles. For example, when it comes to conversion rates, most currencies have determined rules about needed precision and rounding rules (you can have a look at the EUR conversion rate rules here).

结论

本文并未详尽介绍在 JavaScript 中处理金额的所有现有可能性,也无意为您提供完整/完美的货币数据模型。我试图为您提供足够的提示和指南,以实施一种被证明是一致的、有弹性的、由金融科技行业的大人物选择的表示形式。我希望你能够在未来的项目中进行金额计算,而不会忘记口袋里的任何一分钱(否则别忘了看看你的旧夹克)!

以上是JavaScript 中的财务精确度:处理金钱而不损失一分钱的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:dev.to
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板