C# Decimal and Money
Use decimal for a small fee calculation and make the midpoint-rounding policy visible.
How it works
decimal represents base-ten values with a finite precision and range. It is useful for many money calculations because common decimal fractions can be represented exactly, but it does not decide taxation, currency units or rounding policy. The m suffix makes a literal decimal rather than double. Round at the boundary required by the business rule, not repeatedly after every intermediate operation. Format with an explicit culture when a test or exported record requires one stable representation.
Run it locally
Use the .NET 10 SDK with C# 14 in a separate console lab. Create an empty project once with dotnet new console --framework net10.0, then replace Program.cs with this complete source and add any supporting files shown. Keep only one lesson entry point in the project. C# does not currently run in Bhylu’s browser playground. Apache, PHP and MySQL are not needed.
dotnet build -p:LangVersion=14.0 -p:Nullable=enable -p:TreatWarningsAsErrors=true
dotnet run --no-buildUse the SDK’s project workflow; the review compiles against its matching reference assemblies and executes the results without external NuGet packages. File-writing examples belong in a private empty lab directory.
Example
using System;
using System.Globalization;
internal static class Program
{
private static void Main(string[] args)
{
decimal fee = 12.50m;
int attendees = 3;
decimal total = fee * attendees;
Console.WriteLine(total.ToString("F2", CultureInfo.InvariantCulture));
decimal rounded = Math.Round(2.345m, 2, MidpointRounding.AwayFromZero);
Console.WriteLine(rounded.ToString("F2", CultureInfo.InvariantCulture));
}
}
Expected result
37.50
2.35
The total has two decimal places in its display and the explicit rounding policy moves the midpoint away from zero. Another domain might require ties-to-even or rounding at invoice level. Decimal can still overflow or require rounding for division, so a financial data model must state its maximum amounts and accepted scale.
Consult Microsoft’s C# documentation for language and library contracts, including target-framework and version requirements.