在快节奏的金融世界中,精确性就是一切。最好避免因舍入/精度错误而造成百万美元的损失。
说到金钱,请考虑数据类型
本文的出发点是认识到金钱并不是你可以用来数篮子里苹果的平均基本数字。当您尝试将 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中文网其他相关文章!

Python更适合初学者,学习曲线平缓,语法简洁;JavaScript适合前端开发,学习曲线较陡,语法灵活。1.Python语法直观,适用于数据科学和后端开发。2.JavaScript灵活,广泛用于前端和服务器端编程。

Python和JavaScript在社区、库和资源方面的对比各有优劣。1)Python社区友好,适合初学者,但前端开发资源不如JavaScript丰富。2)Python在数据科学和机器学习库方面强大,JavaScript则在前端开发库和框架上更胜一筹。3)两者的学习资源都丰富,但Python适合从官方文档开始,JavaScript则以MDNWebDocs为佳。选择应基于项目需求和个人兴趣。

从C/C 转向JavaScript需要适应动态类型、垃圾回收和异步编程等特点。1)C/C 是静态类型语言,需手动管理内存,而JavaScript是动态类型,垃圾回收自动处理。2)C/C 需编译成机器码,JavaScript则为解释型语言。3)JavaScript引入闭包、原型链和Promise等概念,增强了灵活性和异步编程能力。

不同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实现跨平台开发,提高开发效率。


热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

AI Hentai Generator
免费生成ai无尽的。

热门文章

热工具

螳螂BT
Mantis是一个易于部署的基于Web的缺陷跟踪工具,用于帮助产品缺陷跟踪。它需要PHP、MySQL和一个Web服务器。请查看我们的演示和托管服务。

适用于 Eclipse 的 SAP NetWeaver 服务器适配器
将Eclipse与SAP NetWeaver应用服务器集成。

VSCode Windows 64位 下载
微软推出的免费、功能强大的一款IDE编辑器

SublimeText3 英文版
推荐:为Win版本,支持代码提示!

ZendStudio 13.5.1 Mac
功能强大的PHP集成开发环境