Understanding the BigDouble Subtraction Bug in Flutter

If you are developing an incremental game or handling large numerical values in Flutter using the big_double package (specifically around version 1.0.2), you might encounter a puzzling bug: addition, multiplication, and division work perfectly, but subtraction fails and returns the original value unchanged.

BigDouble currentHealth = 5.big;
print(currentHealth / 2.big); // 2.5
print(currentHealth + 2.big); // 7
print(currentHealth - 2.big); // 5 (Expected: 3)
print(currentHealth * 2.big); // 10

Why Is Subtraction Failing?

This issue stems from an implementation bug in version 1.0.2 of the big_double package. The subtraction operator (-) in that specific release contained a logic flaw during mantissa and exponent realignment, causing the operation to return the left-hand operand without performing the subtraction.

How to Fix the Issue

Solution 1: Upgrade the big_double Package

The simplest fix is to update your package dependency to a patched version where operator overloading for subtraction is resolved. Open your pubspec.yaml file and update the package version:

dependencies:
  big_double: ^1.0.3 # Or the latest available version

After updating, run the following command in your terminal:

flutter pub get

Solution 2: Use the Production-Ready decimal Package (Recommended)

If you require high precision for floating-point calculations and want to avoid bugs in unmaintained libraries, migrating to the official Dart decimal package is the best approach.

Add decimal to your pubspec.yaml:

dependencies:
  decimal: ^2.3.3

Here is how to rewrite your logic using Decimal:

import 'package:decimal/decimal.dart';

void main() {
  final currentHealth = Decimal.parse('5');
  final amount = Decimal.parse('2');

  print(currentHealth / amount); // 2.5
  print(currentHealth + amount); // 7
  print(currentHealth - amount); // 3 (Works as expected!)
  print(currentHealth * amount); // 10
}

Conclusion

If subtraction with BigDouble yields unexpected results, it is almost certainly due to an internal bug in package version 1.0.2. Updating the package or switching to a stable alternative like decimal or Dart's built-in BigInt will resolve the problem cleanly.