Money.fromNum constructor
Money.from
Creates an instance of Money from a num holding the monetary value. Unlike Money.fromBigInt the amount is in dollars and cents (not just cents).
This means that you can intiate a Money value from a double or int as follows:
Money buyPrice = Money.from(10);
print(buyPrice.toString());
> $10.00
Money sellPrice = Money.from(10.50);
print(sellPrice.toString());
> $10.50
NOTE: be very careful using doubles to transport money as you are guarenteed to get rounding errors!!! You should use a String with Money.parse().
amount
- the monetary value.
isoCode
- the currency isoCode of the amount
. This must be either one
of the CommonCurrencies or a currency you have registered
via Currencies.register.
If the decimalDigits
is provided then the Money instance is
created with the supplied number of decimalDigits
.
If decimalDigits
isn't provided then the decimalDigits
is taken
from the Currency associated with the isoCode
.
Throws an UnknownCurrencyException if the isoCode
is not a registered
isoCode.
Implementation
/// Creates an instance of [Money] from a [num] holding the monetary value.
/// Unlike [Money.fromBigInt] the amount is in dollars and cents
/// (not just cents).
///
/// This means that you can intiate a Money value from a double or int
/// as follows:
/// ```dart
/// Money buyPrice = Money.from(10);
/// print(buyPrice.toString());
/// > $10.00
/// Money sellPrice = Money.from(10.50);
/// print(sellPrice.toString());
/// > $10.50
/// ```
/// NOTE: be very careful using doubles to transport money as you are
/// guarenteed to get rounding errors!!! You should use a [String]
/// with [Money.parse()].
///
/// [amount] - the monetary value.
/// [isoCode] - the currency isoCode of the [amount]. This must be either one
/// of the [CommonCurrencies] or a currency you have registered
/// via [Currencies.register].
/// If the [decimalDigits] is provided then the [Money] instance is
/// created with the supplied number of [decimalDigits].
/// If [decimalDigits] isn't provided then the [decimalDigits] is taken
/// from the [Currency] associated with the [isoCode].
/// Throws an [UnknownCurrencyException] if the [isoCode] is not a registered
/// isoCode.
factory Money.fromNum(num amount,
{required String isoCode, int? decimalDigits}) {
final currency = Currencies().find(isoCode);
if (currency == null) {
throw UnknownCurrencyException(isoCode);
}
return Money.fromNumWithCurrency(amount, currency,
decimalDigits: decimalDigits ?? currency.decimalDigits);
}