Dart:存储货币的最佳类型

Dart: best type to store currency

在Java中,货币通常存储在BigDecimal中。但是在 Dart 中用什么来存储货币值呢? BigInt 似乎不是解决方案,因为它仅适用于整数值。

绝对double用于会计应用程序。二进制浮点数本身不能表示精确的十进制值,这会导致 inaccurate calculations for seemingly trivial operations。尽管错误很小,但它们最终会累积成更大的错误。为二进制数设置小数精度没有意义。

对于货币,您应该使用一些旨在存储小数值的东西(例如 package:decimal) or should use fixed-point arithmetic 来存储美分(或者您要跟踪的最小货币数量)。例如,而不是使用doubles 存储值,如 $1.23,使用 ints 存储最小货币单位的金额(例如 123 美分)。然后你可以使用助手 类 来格式化金额它们被显示出来。例如:

class Money {
   int cents;

   Money({required this.cents});

   @override
   String toString() => (cents / 100).toStringAsFixed(2);

   Money operator +(Money other) => Money(cents: cents + other.cents);

   // Add other operations as desired.
}