Dart implementation of Fowler's Money pattern.
// Create a money object that represents 1 USD
final money = Money(100, Currency('USD'));
// Access the Money object's monetary value
print(money.amount); // => 100
// -- OR --
print(money.amountAsString); // => 1.00
final money = Money.fromString('12.50', Currency('USD'));
print(money.amount); // => 1250
final money = Money.fromDouble(12.34, Currency('USD'));
print(money.amount); // => 1234
final money = Money(150, Currency('USD'));
print(money.toString()); // => 1.50 USD
// Create two Money objects that represent 1 USD and 2 USD, respectively
final a = Money(100, Currency('USD'));
final b = Money(200, Currency('USD'));
var c = null;
// Negate a Money object
c = -a;
print(c); // => -1.00 USD
// Calculate the sum of two Money objects
c = a + b;
print(c); // => 3.00 USD
// Calculate the difference of two Money objects
c = b - a;
print(c); // => 1.00 USD
// Multiply a Money object with a factor
c = a * 2;
print(c); // => 2.00 USD
final a = Money(100, Currency('USD'));
final b = Money(200, Currency('USD'));
a < b; // => true
a > b; // => false
b <= a; // => false
b => a; // => true
a.compareTo(b); // => -1
a.compareTo(a); // => 0
b.compareTo(a); // => 1
The compareTo()
method returns an integer less than, equal to, or greater than zero if the value of one Money
object is considered to be respectively less than, equal to, or greater than that of another Money
object.
Money
implements Comparable
interface and you can sort a list of Money
objects.
final a = Money(5, Currency('USD'));
for (var c in a.allocate(3, 7)) {
print(c);
}
The code above produces the output shown below:
2
3