money2
  • Overview
  • Common Currencies
  • Creating a Currency
  • Registering a Currency
  • Parsing
  • Find a currency
  • Default format
  • Symbols
  • Separators
    • Decimal Separator
    • Group Separator
  • Creating Money
    • Money.parse
    • Currency.parse
    • Money.from
    • Currencies.parse
    • decimalDigits
  • Formatting
    • Formatting Patterns
  • Storing and Send
  • Exchange Rates
  • Comparison
  • Currency Predicates
  • Value Sign Predicates
  • Arithmetic Operations
  • Allocation
  • Money encoding/decoding
Powered by GitBook
On this page

Was this helpful?

Allocation

Allocation According to Ratios

Let's say our company has made a profit of 5 cents, which has to be divided amongst two investors that hold 70% and 30%. Cents can't be divided, so we can't give 3.5 and 1.5 cents. If we round up, the first investor gets 4 cents, the investor gets 2, which means we need to conjure up an additional cent.

The best solution to avoid this pitfall is to use allocation according to ratios.

The sum of an allocation is always guarenteed to be equal to the money instance it is called against.

import 'money2.dart';
    test('Ratio', () {
      final usd = CommonCurrencies().usd;
      final profit = Money.fromBigIntWithCurrency(BigInt.from(5), usd); // 5¢

      var allocation = profit.allocationAccordingTo([70, 30]);
      expect(allocation[0],
          equals(Money.fromBigIntWithCurrency(BigInt.from(4), usd))); // 4¢
      expect(allocation[1],
          equals(Money.fromBigIntWithCurrency(BigInt.from(1), usd))); // 1¢

      /// The order of ratios is important:
      allocation = profit.allocationAccordingTo([30, 70]);
      expect(allocation[0],
          equals(Money.fromBigIntWithCurrency(BigInt.from(2), usd))); // 2¢
      expect(allocation[1],
          equals(Money.fromBigIntWithCurrency(BigInt.from(3), usd))); // 3¢
    });

Allocation to N Targets

An amount of money can be allocated to N targets using allocateTo().

import 'money2.dart';
    test('N Targest', () {
      final usd = CommonCurrencies().usd;

      final value =
          Money.fromBigIntWithCurrency(BigInt.from(800), usd); // $8.00

      final allocation = value.allocationTo(3);
      expect(allocation[0],
          equals(Money.fromBigIntWithCurrency(BigInt.from(267), usd))); // $2.67
      expect(allocation[1],
          equals(Money.fromBigIntWithCurrency(BigInt.from(267), usd))); // $2.67
      expect(allocation[2],
          equals(Money.fromBigIntWithCurrency(BigInt.from(266), usd))); // $2.66
    });
PreviousArithmetic OperationsNextMoney encoding/decoding

Last updated 28 days ago

Was this helpful?