The Principal Dev – Masterclass for Tech Leads

The Principal Dev – Masterclass for Tech LeadsNov 27-28

Join

NodaMoney

NuGet NuGet Pre-release NuGet CI

About

NodaMoney provides a library that treats Money as a first class citizen in .NET and handles all the ugly bits like currencies and formatting.

We have the decimal type in .NET to store an amount of money, which can be used for very basic things. But it's still a numeric value without knowledge about its currency, major and minor units, formatting, etc. The .NET Framework has the System.Globalization namespace that helps with formatting of money in different cultures and regions, but it only captures some info about currencies, but not everything.

There is also some business logic surrounding money, like dividing without losing pennies (like in the movie Office Space), conversion, etc. that motivates to have a Money type that contains all the domain logic, like Martin Fowler already described in his book Patterns of Enterprise Application Architecture, see pages about Money and Quantity.

NodaMoney represents the .NET counterpart of java library JodaMoney, like NodaTime is the .NET counterpart of JodaTime. NodaMoney does not provide, nor is it intended to provide, monetary algorithms beyond the most basic and obvious. This is because the requirements for these algorithms vary widely between domains. This library is intended to act as the base layer, providing classes that should be in the .NET Framework. It complies with the currencies in ISO 4217.

Basic Usage

The main classes are:

Initializing money

// Define money with explicit currency
Money euros = new Money(6.54m, "EUR");
Money euros = new (6.54m, "EUR");
Money euros = new Money(6.54m, Currency.FromCode("EUR"));
Money euros = new Money(6.54m, CurrencyInfo.FromCode("EUR"));

// From existing money
Money dollars = euros with { Currency = CurrencyInfo.FromCode("USD") };
Money myEuros = euros with { Amount = 10.12m };

// Define money explicit using helper method for most used currencies in the world
Money euros = Money.Euro(6.54m);
Money dollars = Money.USDollar(6.54m);
Money pounds = Money.PoundSterling(6.54m);
Money yens = Money.Yen(6);

// Implicit Currency based on current culture/region.
// When culture is 'NL-nl' code below results in Euros.
Money euros = new Money(6.54m);
Money euros = new (6.54m);
Money euros = (Money)6.54m;

// Auto-rounding to the minor unit will take place with MidpointRounding.ToEven
// also known as banker's rounding
Money euro = new Money(765.425m, "EUR"); // EUR 765.42
Money euro = new Money(765.425m, "EUR", MidpointRounding.AwayFromZero); // EUR 765.43

// Deconstruct money
Money money = new Money(10m, "EUR");
var (amount, currency) = money;

Money operations

Money euro10 = Money.Euro(10);
Money euro20 = Money.Euro(20);
Money dollar10 = Money.USDollar(10);
Money zeroDollar = Money.USDollar(0);

// Compare money
euro10 == euro20; // false
euro10 != euro20; // true;
euro10 == dollar10; // false;
euro20 > euro10; // true;
euro10 <= dollar10; // throws InvalidCurrencyException!
zeroEuro == zeroDollar; // true; special zero handling

// Add and Substract
Money euro30 = euro10 + euro20;
Money euro10 = euro20 - euro10;
Money m = euro10 + dollar10; // throws InvalidCurrencyException!
Money euro10 = euro10 + zeroDollar; // doesn't throw when adding zero
euro20 += euro10; // EUR 30
euro20 -= euro10; // EUR 10

// Add and Substract with implied Currency Context
Money euro30 = euro10 + 20m; // decimal value is assumed to have the same currency context
Money euro10 = euro20 - 10m; // decimal value is assumed to have the same currency context

// Decrement and Increment by minor unit
Money yen = new Money(765m, "JPY"); // the smallest unit is 1 yen
Money euro = new Money(765.43m, "EUR"); // the smallest unit is 1 cent (1EUR = 100 cent)
++yen; // JPY 766
--yen; // JPY 765
++euro; // EUR 765.44
--euro; // EUR 765.43

// Multiply
Money m = euro10 * euro20; // doesn't compile!
Money euro20 = euro10 * 2;
Money discount = euro10 * 0.15m;

// Divide
decimal ratio = euro20 / euro10;
Money euro5 = euro10 / 2;

// Divide without losing money
Money total = new Money(101m, "USD");
IEnumerable<Money> inShares = total.Split(4); // [USD 25, USD 25, USD 25, USD 26]
IEnumerable<Money> byRatio = total.Split([2,1,3]); // [USD 33.67, USD 16.83, USD 50.50]

// Modulus / Remainder
Money total = new Money(105.50m, "USD");
Money unitPrice = new Money(20.00m, "USD"); // USD 20 * 5 = USD 100
Money remainder = total % unitPrice; // USD 5.50

Money formatting

Money yen = new Money(2765m, "JPY");
Money euro = new Money(2765.43m, "EUR");
Money dollar = new Money(2765.43m, "USD");
Money dinar = new Money(2765.432m, "BHD");

// Implicit when current culture is 'en-US'
yen.ToString();    // "¥2,765"
euro.ToString();   // "€2,765.43"
dollar.ToString(); // "$2,765.43"
dinar.ToString();  // "BD2,765.432"

// Implicit when current culture is 'nl-BE'
yen.ToString();    // "¥ 2.765"
euro.ToString();   // "€ 2.765,43"
dollar.ToString(); // "$ 2.765,43"
dinar.ToString();  // "BD 2.765,432"

// Implicit when current culture is 'fr-BE'
yen.ToString();    // "2.765 ¥"
euro.ToString();   // "2.765,43 €"
dollar.ToString(); // "2.765,43 $"
dinar.ToString();  // "2.765,432 BD"

// Explicit format for culture 'nl-NL'
var ci = new CultureInfo("nl-NL");

yen.ToString(ci);    // "¥ 2.765"
euro.ToString(ci);   // "€ 2.765,43"
dollar.ToString(ci); // "$ 2.765,43"
dinar.ToString(ci);  // "BD 2.765,432"

// Standard Formats when currenct culture is 'nl-NL'
euro.ToString("C");  // "€ 2.765,43"    Currency format
euro.ToString("C0"); // "€ 2.765"       Currency format with precision specifier
euro.ToString("G");  // "EUR 2.765,43"  General format (= C but with currency code)
euro.ToString("L");  // "2.765,43 Euro" English name format
euro.ToString("R");  // "EUR 2,765.43"  Round-trip format
euro.ToString("N");  // "2,765.43"      Number format
euro.ToString("F");  // "2765,43"       Fixed point format

Money parsing

// Implicit parsing when current culture is 'nl-BE'
Money euro = Money.Parse("€ 765,43");
Money euro = Money.Parse("-€ 765,43");
Money euro = Money.Parse("€-765,43");
Money euro = Money.Parse("765,43 €");
Money yen = Money.Parse("¥ 765"); // throw FormatException, because ¥ symbol is used for Japanese yen and Chinese yuan
Money dollar = Money.Parse("$ 765,43"); // throw FormatException, because $ symbol is used for multiple currencies

// Implicit parsing when current culture is 'ja-JP'
Money yen = Money.Parse("¥ 765");

// Implicit parsing when current culture is 'zh-CN'
Money yuan = Money.Parse("¥ 765");

// Implicit parsing when current culture is 'en-US'
Money dollar = Money.Parse("$765.43");
Money dollar = Money.Parse("($765.43)"); // -$765.43

// Implicit parsing when current culture is 'es-AR'
Money peso = Money.Parse("$765.43");

// Explicit parsing when current culture is 'nl-BE'
Money euro = Money.Parse("€ 765,43", Currency.FromCode("EUR"));
Money euro = Money.Parse("765,43 €", Currency.FromCode("EUR"));
Money yen = Money.Parse("¥ 765", Currency.FromCode("JPY"));
Money yuan = Money.Parse("¥ 765", Currency.FromCode("CNY"));

// Implicit try parsing when current culture is 'nl-BE'
Money euro;
Money.TryParse("€ 765,43", out euro);

// Explicit try parsing when current culture is 'nl-BE'
Money euro;
Money.TryParse("€ 765,43", Currency.FromCode("EUR"), out euro);

FastMoney

Money type is based on decimal and by default always rounded to the currency minor unit (use MoneyContext to override). Money has 28 digits precision (±1.0 × 10^-28 to ±7.9 × 10^28)

FastMoney type is an optimized version of Money that:

Only use FastMoney when you need the fastest performance, and you know what you're doing regarding currency rounding and don't mind the loss of precision. Convert FastMoney to Money for presentation and formatting.

Usage:

using NodaMoney;

var eur = new FastMoney(10.1234m, "EUR");
var fee = new FastMoney(0.1000m, "EUR");
var total = eur + fee;              // currency-safe operations

// Convert to Money for formatting/rounding/presentation
Money display = eur.ToMoney();      // or (Money)eur
var text = display.ToString("C");

// Convert from Money (explicit)
var money = new Money(12.34m, "EUR");
FastMoney fast = (FastMoney)money;  // or new FastMoney(money)

// Convert from SqlMoney
SqlMoney sqlMoney = db.MoneyFromDb();
FastMoney? fast = FastMoney.FromSqlMoney(sqlMoney, Currency.FromCode("EUR")); // or (FastMoney?)sqlMoney

// Convert to SqlMoney
SqlMoney sqlMoney1 = fast.ToSqlMoney(Currency.FromCode("EUR"));

// Convert from OLE Automation Currency
long oaCurrency = db.CurrencyFromDb();
FastMoney fast = FastMoney.FromOACurrency(oaCurrency, Currency.FromCode("EUR"));

// Convert to OLE Automation Currency
long oaCurrency = fast.ToOACurrency();

Currency(Info)

Currency is a unit of currency that is a small optimized struct that represencts the Currency Code. It is used inside Money and as struct in fast lookups.

CurrencyInfo is a class that contains information about the currency, such as the ISO 4217 code, the symbol, the name, and the minor unit. It is used to create a Currency instance (implicit cast) or to register a custom currency.

Initializing Currency

// Create Currency unit
Currency euro = Currency.FromCode("EUR");

// Create CurrencyInfo (for metadata about Currency)
CurrencyInfo ci = CurrencyInfo.FromCode("EUR");
CurrencyInfo ci = CurrencyInfo.GetInstance(euro); // From Currency unit To CurrencyInfo
Currencyinfo ci = CurrencyInfo.GetInstance(CultureInfo.CurrentCulture);
Currencyinfo ci = CurrencyInfo.GetInstance(RegionInfo.CurrentRegion);
Currencyinfo ci = CurrencyInfo.GetInstance(NumberFormatInfo.InvariantInfo);
CurrencyInfo ci = CurrencyInfo.CurrentCurrency;

Currency euro = ci; // Implicit cast to Currency Unit

Create custom Currency (advanced)

// Create custom currency
CurrencyInfo myCurrency = CurrencyInfo.Create("BTA") with
{
    Symbol = "$",
    Number = 1023,
    InternationalSymbol = "CC$",
    MinorUnit = MinorUnit.Two,
    EnglishName = "My Custom Currency",
    IsIso4217 = false,
    AlternativeSymbols = ["cc$"],
    IntroducedOn = new DateTime(2022, 1, 1),
    ExpiredOn = new DateTime(2030, 1, 1)
};

// Fails because it's not registred
var notExisting = CurrencyInfo.FromCode("BTA"); // throw exception

// Register it for the life-time of the app domain
CurrencyInfo.Register(myCurrency);
var exists = CurrencyInfo.FromCode("BTA"); // returns myCurrency

// Create custom currency based on existing currency
CurrencyInfo myCurrency = CurrencyInfo.FromCode("EUR") with { Code = "EUA", EnglishName = "New Euro" };
CurrencyInfo.Register(myCurrency);

var myEuro = Currency.FromCode("EUA"); // returns myCurrency

// Replace currency for the life-time of the app domain
CurrencyInfo oldEuro = CurrencyInfo.Unregister("EUR");
CurrencyInfo newEuro = oldEuro with { Symbol = "€U", EnglishName = "New Euro" };
CurrencyInfo.Register(newEuro);

var myEuro = Currency.FromCode("EUR"); // returns newEuro

MoneyContext (advanced)

MoneyContext centralizes rounding, scale, and default currency configuration used by Money operations. You can set a global default, create scoped contexts, and integrate it with Microsoft.Extensions.DependencyInjection. Every Money object uses the context it was created in or was given explicitly.

Set own global default without DI:

using NodaMoney;
using NodaMoney.Context;

// Set global default MoneyContext, will be used by all created Money objects
MoneyContext myDefaultContext = MoneyContext.Create(opt =>
{
    opt.MaxScale = 4;
    opt.DefaultCurrency = CurrencyInfo.FromCode("USD");
    opt.EnforceZeroCurrencyMatching = true;
});
MoneyContext.DefaultThreadContext = myDefaultContext;

// or
MoneyContext.CreateAndSetDefault(opt =>
{
    opt.MaxScale = 4;
    opt.DefaultCurrency = CurrencyInfo.FromCode("USD");
    opt.EnforceZeroCurrencyMatching = true;
});

Use MoneyContext by instance or scope:

// Explicit MoneyContext when creating a new Money object
MoneyContext myOwnContext = MoneyContext.Create(opt =>
{
    opt.MaxScale = 2;
    opt.RoundingStrategy = new StandardRounding(MidpointRounding.AwayFromZero);
    opt.DefaultCurrency = CurrencyInfo.FromCode("EUR");
});

Money money1 = new Money(6.54m, "EUR", myOwnContext); // explicit MoneyContext
Money money2 = new Money(6.54m, "EUR"); // implicit global MoneyContext

// This will throw an InvalidOperationException because money1 and money2 have different contexts:
var result = money1 + money2;

// Instead, align contexts using the 'with' expression:
var result = money1 + (money2 with { Context = money1.Context });

// Use MoneyContext in a scope (sets MoneyContext.ThreadContext for the duration of the scope):
using (MoneyContext.CreateScope(myOwnContext))
{
    Money money3 = new Money(10.00m, "EUR");
    Money money4 = new Money(5.00m, "EUR");
    var total = money3 + money4;
}

Use MoneyContext with Dependency Injection (Nuget: NodaMoney.DependencyInjection):

using Microsoft.Extensions.DependencyInjection;
using NodaMoney;
using NodaMoney.Context;
using NodaMoney.DependencyInjection; // NuGet: NodaMoney.DependencyInjection

var builder = WebApplication.CreateBuilder(args);

// Register MoneyContext with custom options as default global context
builder.Services.AddMoneyContext(options =>
{
    options.DefaultCurrency = Currency.FromCode("USD");
    options.RoundingStrategy = new StandardRounding(MidpointRounding.AwayFromZero);
    options.MaxScale = 2;
    opt.EnforceZeroCurrencyMatching = true;
});

var app = builder.Build();

// Consume MoneyContext via DI
app.MapGet("/total", (MoneyContext context) =>
{
    Console.WriteLine(context.DefaultCurrency); // returns "USD"

    var price = new Money(10m, "USD"); // uses registered default context
    return price.Round().ToString("C");
});

app.Run();

You can also configure via IConfiguration (appsettings.json) and register multiple named contexts. See the NodaMoney.DependencyInjection README for full examples.

Releases

This library uses Semantic Versioning to give meaning to the version numbers.

You can get the latest stable release or prerelease from the official Nuget.org feed or from our GitHub releases page.

If you'd like to work with the bleeding edge, you can use our GitHub Nuget feed. Packages on this feed are alpha and beta and, while they've passed all our tests, are not yet ready for production.

Support

For support, bugs and new ideas use GitHub issues.

For supporting the project:

Contributing

Your contributions are always welcome! Please have a look at the contribution guidelines first.

Previous contributors include:

Made with contrib.rocks.

Credits

This library wouldn't have been possible without the following tools, packages, and companies:

License

This project is licensed under the Apache License - see the LICENSE file for details.

Join libs.tech

...and unlock some superpowers

GitHub

We won't share your data with anyone else.