首頁 > web前端 > js教程 > 主體

JavaScript 中的財務精確度:處理金錢而不損失一分錢

WBOY
發布: 2024-08-10 06:45:02
原創
789 人瀏覽過

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
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!