ModelPrice class
Represents an immutable monetary amount stored in minor units, with its decimal precision and currency.
Values are stored in amount (minor units). The decimal value is derived as:
decimalAmount = amount / pow(10, mathPrecision).
Contracts
amountmust be non-negative.mathPrecisionmust be non-negative (defaults to defaultMathprecision).currencyis required and encoded/decoded by its enum name (e.g."COP").- JSON shape:
{ "amount": int, "mathPrecision": int, "currency": String }.
Minimal runnable example
void main() {
// 12.50 COP represented as 1250 minor units with precision 2
final ModelPrice price = ModelPrice(
amount: 1250,
currency: CurrencyEnum.COP,
mathPrecision: ModelPrice.defaultMathprecision, // 2
);
print(price.decimalAmount); // 12.5
print(price.toJson()); // {amount: 1250, mathPrecision: 2, currency: COP}
print(price); // 💰 12.50 COP
// copyWith normalizes negatives: amount -> abs, precision -> non-negative
final ModelPrice updated = price.copyWith(amount: -1999, mathPrecision: -1);
print(updated.amount); // 1999
print(updated.mathPrecision); // 2 (fallback to default)
}
Notes
decimalAmountuses floating-point division; for display, prefertoString()ortoStringAsFixed(mathPrecision)to avoid rounding artifacts.
Constructors
- ModelPrice({required int amount, required CurrencyEnum currency, int mathPrecision = defaultMathprecision})
-
Creates a new immutable ModelPrice.
const
-
ModelPrice.fromJson(Map<
String, dynamic> json) -
Builds a ModelPrice from a JSON map.
factory
Properties
- amount → int
-
Amount in minor units (scaled by mathPrecision); must be non-negative.
final
- currency → CurrencyEnum
-
ISO-like currency code from CurrencyEnum (e.g.,
COP,USD,EUR).final - decimalAmount → double
-
Decimal representation computed as
amount / pow(10, mathPrecision).no setter - hashCode → int
-
Hash code consistent with equality.
no setteroverride
- mathPrecision → int
-
Number of decimal places used to scale amount.
final
- runtimeType → Type
-
A representation of the runtime type of the object.
no setterinherited
Methods
-
copyWith(
{int? amount, int? mathPrecision, CurrencyEnum? currency}) → ModelPrice -
Returns a new ModelPrice overriding the provided fields.
override
-
noSuchMethod(
Invocation invocation) → dynamic -
Invoked when a nonexistent method or property is accessed.
inherited
-
toJson(
) → Map< String, dynamic> -
Serializes this price to JSON:
{ "amount": int, "mathPrecision": int, "currency": String }.override -
toString(
) → String -
Human-readable representation (e.g.,
💰 12.50 COP).override
Operators
-
operator ==(
Object other) → bool -
Structural equality on
amount,mathPrecision, andcurrency.override
Constants
- defaultMathprecision → const int
- Default decimal precision used when not provided.