在快節奏的金融世界中,精確性就是一切。最好避免因舍入/精度錯誤而造成百萬美元的損失。
說到金錢,請考慮資料類型
本文的出發點是認識到金錢並不是你可以用來數籃子裡蘋果的平均基本數字。當您嘗試將 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 </stdio.h>
// 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
然後,您需要使用以下公式將您的位元表示形式轉換為十進位值:
雙精確度浮點數表示的範例,近似為 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.
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中文網其他相關文章!

不同JavaScript引擎在解析和執行JavaScript代碼時,效果會有所不同,因為每個引擎的實現原理和優化策略各有差異。 1.詞法分析:將源碼轉換為詞法單元。 2.語法分析:生成抽象語法樹。 3.優化和編譯:通過JIT編譯器生成機器碼。 4.執行:運行機器碼。 V8引擎通過即時編譯和隱藏類優化,SpiderMonkey使用類型推斷系統,導致在相同代碼上的性能表現不同。

JavaScript在現實世界中的應用包括服務器端編程、移動應用開發和物聯網控制:1.通過Node.js實現服務器端編程,適用於高並發請求處理。 2.通過ReactNative進行移動應用開發,支持跨平台部署。 3.通過Johnny-Five庫用於物聯網設備控制,適用於硬件交互。

我使用您的日常技術工具構建了功能性的多租戶SaaS應用程序(一個Edtech應用程序),您可以做同樣的事情。 首先,什麼是多租戶SaaS應用程序? 多租戶SaaS應用程序可讓您從唱歌中為多個客戶提供服務

本文展示了與許可證確保的後端的前端集成,並使用Next.js構建功能性Edtech SaaS應用程序。 前端獲取用戶權限以控制UI的可見性並確保API要求遵守角色庫

JavaScript是現代Web開發的核心語言,因其多樣性和靈活性而廣泛應用。 1)前端開發:通過DOM操作和現代框架(如React、Vue.js、Angular)構建動態網頁和單頁面應用。 2)服務器端開發:Node.js利用非阻塞I/O模型處理高並發和實時應用。 3)移動和桌面應用開發:通過ReactNative和Electron實現跨平台開發,提高開發效率。

JavaScript的最新趨勢包括TypeScript的崛起、現代框架和庫的流行以及WebAssembly的應用。未來前景涵蓋更強大的類型系統、服務器端JavaScript的發展、人工智能和機器學習的擴展以及物聯網和邊緣計算的潛力。

JavaScript是現代Web開發的基石,它的主要功能包括事件驅動編程、動態內容生成和異步編程。 1)事件驅動編程允許網頁根據用戶操作動態變化。 2)動態內容生成使得頁面內容可以根據條件調整。 3)異步編程確保用戶界面不被阻塞。 JavaScript廣泛應用於網頁交互、單頁面應用和服務器端開發,極大地提升了用戶體驗和跨平台開發的靈活性。

Python更适合数据科学和机器学习,JavaScript更适合前端和全栈开发。1.Python以简洁语法和丰富库生态著称,适用于数据分析和Web开发。2.JavaScript是前端开发核心,Node.js支持服务器端编程,适用于全栈开发。


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

AI Hentai Generator
免費產生 AI 無盡。

熱門文章

熱工具

Safe Exam Browser
Safe Exam Browser是一個安全的瀏覽器環境,安全地進行線上考試。該軟體將任何電腦變成一個安全的工作站。它控制對任何實用工具的訪問,並防止學生使用未經授權的資源。

MantisBT
Mantis是一個易於部署的基於Web的缺陷追蹤工具,用於幫助產品缺陷追蹤。它需要PHP、MySQL和一個Web伺服器。請查看我們的演示和託管服務。

SAP NetWeaver Server Adapter for Eclipse
將Eclipse與SAP NetWeaver應用伺服器整合。

SublimeText3 英文版
推薦:為Win版本,支援程式碼提示!

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)