Money2는 통화 및 금액의 저장, 파싱, 포맷팅 및 산술 연산을 위한 고정밀 라이브러리입니다. 고정 소수점 수학, 다중 통화 지원 및 변환, 파싱 및 포맷팅. (Money.parse('$2010.00') * 10).format('SCC#,##0') -> $US20,100
Money2는 다중 통화에서 금액을 정확하게 처리하기 위해 설계된 고정밀도 Dart 라이브러리입니다. 고정 소수점 연산, 통화 파싱 및 포맷팅, 그리고 통화 간 원활한 변환을 지원합니다. 부동소수점 오류 없이 정확한 계산이 필요한 금융 애플리케이션에 적합하며, '$2010.00'을 파싱하고 10배 곱한 후 '$US20,100' 형식으로 포맷하는 등의 작업을 가능하게 합니다. 이 라이브러리는 모든 주요 플랫폼에서 강력한 지원을 제공하여 금융 계산의 신뢰성을 보장합니다.
사용 사례
금융 응용 프로그램
환율 변환
청구서 및 결제 처리
예산 도구
전자상거래 시스템
회계 소프트웨어
주요 기능
고정밀 소수 연산
다중 통화 지원
통화 파싱 및 형식 지정
내장 통화 변환
플랫폼에 관계없는(모든 주요 플랫폼)
안전한 고정 소수점 수학
적합한 대상
금융 앱을 개발하는 개발자
정확한 금액 계산이 필요한 앱
크로스 플랫폼 금융 도구
국제 통화 처리가 필요한 시스템
고려 사항
명시적인 통화 정의가 필요합니다
사전 정의된 통화 코드로 제한
환율 변환을 위해 외부 환율 정보원에 의존합니다
비금전적 소수 데이터에 적합하지 않음
원본 README
연결된 소스 저장소의 README 원문 스냅샷입니다. 최신 내용은 저장소에서 확인하세요.
Money2
Money2 is a high-precision Dart library for storing, parsing, formatting,
and performing arithmetic on monetary values and currencies.
Overview
Money2 provides safe, precise, and expressive handling of money and currencies.
It’s designed for business and financial applications where accuracy and
predictability are essential — no floating-point rounding surprises.
Key Features
Fixed-precision storage for accurate financial math
Multi-currency support, including custom currencies
final usd = Currency.create(
'USD',
3, // three decimal places
symbol: r'$',
pattern: 'S#,##0.000', // three decimal places
country: 'United States',
unit: 'Dollar',
name: 'United States Dollar',
);
// Now use your custom currencyMoney amount = Money.parseWithCurrency(r'$10.000', usd);
Overriding CommonCurrencies
When parsing an amount that includes an ISO code, the parser searches all
registered currencies for a match.
The CommonCurrencies list is automatically registered, but you can register
additional currencies or override existing ones.
For example, you might want to increase the number of decimal places:
Money2 provides an easy way to convert between currencies using ExchangePlatform.
final aud = CommonCurrencies().aud;
final usd = CommonCurrencies().usd;
// Define an exchange rate: 1 AUD = 0.65 USDfinal rate = ExchangeRate.fromNum(
0.65,
decimalDigits: 8,
fromIsoCode: 'AUD',
toIsoCode: 'USD',
);
// Register one or more exchange rates.final platform = ExchangePlatform()..register(rate);
final audAmount = Money.fromNum(100, isoCode: 'AUD');
final usdAmount = platform.exchangeTo(audAmount, 'USD');
print(usdAmount); // $65.00
If the reverse rate isn’t registered, Money2 can apply the inverse automatically (configurable).
Precision & Safety
All arithmetic uses the Fixed package for fixed-scale (decimal places) operations — no binary
floating-point drift.
Each Money value retains the precision defined by its Currency.
final m = Money.parse(r'$0.10', isoCode: 'USD');
print(m.amount); // Fixed(0.10)print(m.minorUnits); // 10 (cents)
Working with Money
Creating Money Instances
Money2 provides multiple constructors for creating Money objects, depending
on your data source and precision requirements.
All constructors require either a Currency instance or an ISO code
that matches a registered currency (e.g. from CommonCurrencies).
1. From integer minor units
Use Money.fromIntWithCurrency() or Money.fromInt() when you already
have amounts in minor units (e.g. cents, pence).
final usd = CommonCurrencies().usd;
final amount = Money.fromIntWithCurrency(1050, usd);
print(amount); // $10.50
If you have an ISO code instead of a Currency:
final amount = Money.fromInt(1050, isoCode: 'USD');
print(amount); // $10.50
2. From numeric (major units)
Use Money.fromNum() when your source value is in major units (e.g. 10.50 dollars).
Money2 converts this into the correct minor units internally using the currency’s scale.
final amount = Money.fromNum(10.50, isoCode: 'USD');
print(amount); // $10.50
⚠️ Note: Avoid using double for storage or transport — it may introduce binary rounding errors.
Always prefer integer minor units when persisting data.
3. From strings (parsing)
Use Money.parse() or Money.parseWithCurrency() to create money from formatted strings.
final amount = Money.parse(r'$USD10.50');
print(amount); // $10.50final usd = CommonCurrencies().usd;
final parsed = Money.parseWithCurrency(r'$10.50', usd);
print(parsed); // $10.50
Patterns are flexible — see the “Parsing & Formatting” section for details.
4. Using the Currency factory
Create a Currency once, then use it to create multiple Money instances.
final aud = Currency.create('AUD', 2, symbol: r'$', country: 'Australia');
final price = Money.fromIntWithCurrency(1999, aud);
final discount = Money.fromNum(5.50, isoCode: 'AUD');
5. From JSON
Use Money.fromJson() to recreate Money objects from stored JSON.
This is ideal when persisting values in databases or APIs.
final json = {
'minorUnits': 1050,
'decimals': 2,
'isoCode': 'USD'
};
final amount = Money.fromJson(json);
print(amount); // $10.50
6. Cloning and modifying
Because Money is immutable, you can’t modify an existing instance directly.
Instead, use simple arithmetic or the copyWith method.
final price = Money.fromInt(1000, isoCode: 'USD');
final discounted = price * 0.9; // $9.00final highPrecision = price.copyWith(decimalDigits: 4);
Summary
Method
Description
Example
fromIntWithCurrency()
From integer minor units with a Currency
Money.fromIntWithCurrency(1050, usd)
fromInt()
From integer minor units using ISO code
Money.fromInt(1050, isoCode: 'USD')
fromNum()
From numeric (major units)
Money.fromNum(10.50, isoCode: 'USD')
parse() / parseWithCurrency()
From formatted string
Money.parse(r'$USD10.50')
fromJson()
From serialized JSON
Money.fromJson(json)
Math Operations
Money2 supports precise arithmetic operations on Money values, preserving
currency, scale, and rounding rules automatically.
Supported operators
Operator
Description
Example
+ / -
Add or subtract Money values
m1 + m2, m1 - m2
* / /
Multiply or divide by numbers
m1 * 1.1, m1 / 2
~/
Integer division (truncating)
m1 ~/ 3
%
Remainder (modulo)
m1 % Money.fromInt(100, m1.currency)
compareTo / <, >, <=, >=
Comparison operators
if (m1 > m2) print('More')
==
Value equality (same currency + amount)
if (m1 == m2)
All arithmetic operations preserve the currency and decimalDigits of
the operands. When combining two Money values, they must share the same
currency — otherwise a MoneyException is thrown.
Examples
final usd = CommonCurrencies().usd;
final price = Money.fromIntWithCurrency(1000, usd); // $10.00final tax = price * 0.1; // $1.00final total = price + tax; // $11.00final split = total / 3; // $3.67 (rounded)print(total); // $11.00print(split); // $3.67// Comparisonfinal discount = Money.fromIntWithCurrency(200, usd); // $2.00if (discount < total) {
print('Discount is less than total');
}
Parsing & Formatting (Locale-Agnostic Patterns)
Money2 uses simple patterns for parsing and formatting.
Patterns are locale-agnostic — they always use , for grouping and . for decimals.
When formatting, these are replaced by the currency’s actual separators.
Pattern symbols
Symbol
Meaning
S
Currency symbol
C
ISO code
#
Digit placeholder
0
Mandatory digit
.
Decimal separator
,
Group separator
+
Always display +/- sign
-
Display - sign if negative
;
Separate positive/negative patterns
final parsed = usd.parse(r'$10.00');
print(parsed.format('SCCC 0.00')); // $USD 10.00final parsedEur = eur.parse(r'$10.00');
// The decimal separator is based on the currency, not the pattern.print(parsedEur.format('SCCC 0.00+')); // €EUR 10,00+// Separate positive/negative patterns.final clf = Currency.create('CLF', 2,
symbol: 'UF',
pattern: 'S#,##0.00;S-#,##0.00',
);
final value = Money.fromIntWithCurrency(1234, clf);
print(value.toString()); // UF12.34print((-value).toString()); // UF-12.34
Storing Monetary Values
Money stores values in minor units (like cents) using the Fixed type
for deterministic math.