Dart Library that solve the floating point issue by using BigInt
.
Note: DartDecimal
supports precision up to 18 digits because it uses int
instead of BigInt
. The purpose is to avoid unnecessarily large numbers or high precision, as they weren't needed for my use case. Additionally, int
uses a fixed amount of memory and may be more efficient than BigInt
.
# pubspec.yaml
dependencies:
dart_decimal:
git:
url: [email protected]:zdirnecamlcs96/dart-decimal.git
ref: main
$ flutter pub upgrade dart_decimal
// 1.005 * 1000 = 1004.9999999999999
final a = DartDecimal(amount: 1005, precision: 3);
final b = DartDecimal.parse(1000);
final result = a - b; // 1.005
When performing calculations with limited precision (e.g., rounding to 10 decimal places), discrepancies can arise if intermediate results are rounded too early. Rounding early may cause small errors when those rounded values are used in subsequent calculations, leading to minor discrepancies in the final result.
// No rounding until the final result (a / b * c)
final a = DartDecimal.parse(114.4);
final b = DartDecimal.parse(15.2);
final c = a / b; // 7.526315789473684 (full precision)
final result = c * b; // 114.4 (exact result)
// Intermediate rounding (a / b).roundTo(10) * c
final a = DartDecimal.parse(114.4);
final b = DartDecimal.parse(15.2);
final c = (a / b)roundToPrecision(10); // 7.5263157895 (rounded to 10 decimal places)
final result = c * b; // 114.4000000004 (slight discrepancy due to rounding)
- Avoid Intermediate Rounding to prevent such discrepancies.
- For the use case above, check if
b
is the same as thec
and returna
directly without further manipulation to ensure the expected outcome.
This project is intended for personal use only. Use at your own risk. No warranty or support is provided. However, you are welcome to raise issues or submit pull requests.
This project is licensed under the MIT License.
- Inspired by dart-decimal.
- Learned about scientific notation from MathsIsFun.