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
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
Last updated
Was this helpful?