# Money encoding/decoding

API for encoding/decoding a money value enables an application to store values in a database or send over a network.

A money value can be encoded to any type. For example it can be coded as a string in the format like 'USD 5.00'.

Note: this is a trivial example and you would simply use the parse/format methods to encode/decode from/to a string.

#### Encoding

```dart
import 'package:money2/money2.dart';

class MoneyToStringEncoder implements MoneyEncoder<String> {
  @override
  String encode(MoneyData data) {
    // Receives MoneyData DTO and produce
    // a string representation of money value...
    final major = data.integerPart.toString();
    final minor = data.decimalPart.toString();

    return '${data.currency.isoCode} $major.${Strings.padRight(minor, 2, '0')}';
  }


    test('Encoding', () {
      final fiveDollars = Money.parse('5.00', isoCode: 'USD');
      final encoded = fiveDollars.encodedBy(MoneyToStringEncoder());
      // Now we can save `encoded` to database...
      expect(encoded, equals('USD 5.00'));
    });

```

#### Decoding

```dart
import 'package:money2/money2.dart';
class StringToMoneyDecoder implements MoneyDecoder<String> {

  Currencies _currencies;

  StringToMoneyDecoder(this._currencies) {
    if (_currencies == null) {
      throw ArgumentError.notNull('currencies');
    }
  }

  /// Returns decoded `MoneyData` or throws a `FormatException`.
  MoneyData decode(String encoded) {
    // If `encoded` has an invalid format throws FormatException;

    // Extracts currency code from `encoded`:
    final currencyCode = ...;

    // Tries to find information about a currency:
    final currency = _currencies.find(currencyCode);
    if (currency == null) {
      throw FormatException('Unknown currency: $currencyCode.');
    }

    // Using `currency.precision`, extracts minorUnits from `encoded`:
    final minorUnits = ...;

    return MoneyData.from(minorUnits, currency);
  }
}
```

```dart
import 'money2.dart';
try {
  final value = Money.decoding('USD 5.00', MyMoneyDecoder(myCurrencies));

  // ...
} on FormatException {
  // ...
}
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://money2.onepub.dev/money-encoding-decoding.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
