C# Reference ยท Numbers and Math
C# decimal arithmetic
Reference for C# decimal arithmetic: exact base-10 math, scale and trailing zeros, Round, Truncate, Math methods, overflow and money-handling advice.
decimal is a 128-bit base-10 number type with 28 to 29 significant digits. Unlike double, it stores digits in decimal, so values like 0.1 and 19.99 are exact, and sums of such values stay exact. That makes it the right default for money, tax, quantities and any figure a person writes with decimal digits. It is slower than double and has a smaller range (about ยฑ7.9 ร 10ยฒโธ), so it is a poor fit for scientific work.
A decimal remembers its scale: the number of digits after the decimal point. 1.5m and 1.50m are equal but print differently. Arithmetic carries the scale along: adding gives the larger scale, and multiplying adds the scales.
decimal total = 0.1m + 0.2m; // exactly 0.3 Console.WriteLine(total == 0.3m); // True
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.
Syntax
decimal price = 19.99m; // the m suffix makes a decimal literal public static decimal decimal.Round(decimal d, int decimals, MidpointRounding mode) public static decimal decimal.Truncate(decimal d) public static decimal decimal.Floor(decimal d) public static decimal decimal.Ceiling(decimal d) public static decimal decimal.Add(decimal d1, decimal d2) // also Subtract, Multiply, Divide, Remainder, Negate public static decimal decimal.Parse(string s, NumberStyles style, IFormatProvider? provider) public static int[] decimal.GetBits(decimal d) public static decimal decimal.Clamp(decimal value, decimal min, decimal max) public const decimal decimal.MaxValue // 79228162514264337593543950335 public const decimal decimal.MinValue
| Name | Description |
|---|---|
d, d1, d2 |
Decimal operands. |
decimals |
Digits to keep after the decimal point (0 to 28). |
mode |
ToEven (default), AwayFromZero, ToZero, ToNegativeInfinity or ToPositiveInfinity. |
Returns: a decimal. The Math methods Round, Floor, Ceiling, Truncate, Abs, Sign, Max, Min and Clamp all have decimal overloads. Trigonometry, Sqrt, Pow and Log do not; convert to double, calculate, and convert back.
Errors: OverflowException when a result exceeds the range (always, even in unchecked code), and DivideByZeroException when dividing by zero, unlike double.
Usage notes
- Literals need
m.decimal d = 0.1;does not compile because0.1is adouble. Write0.1m. Mixingdecimalwithdoublein an expression is a compile error: convert explicitly. - Casting from
doubleis lossy in a visible way.(decimal)0.1gives0.1because the conversion rounds to 15 significant digits, but this hides real errors in the double. Start from decimal literals or parse text. - Rounding rules.
decimal.RoundandMath.Rounduse banker's rounding (ties to even) unless you pass aMidpointRoundingmode. Choose the rule your accounting requires and apply it at defined points, not after every operation. - Scale and display. Trailing zeros survive operations. Format with
ToString("F2")orN2for output. Do not rely onToString()of a computed decimal to have a fixed number of digits. - Division is not always exact.
1m / 3mis a 28-digit approximation, and1m / 3m * 3mdoes not give exactly1. Allocate remainders explicitly, as in the split example above. - Performance. Decimal operations are software-implemented and several times slower than
double. Usedoublefor simulation and graphics,decimalfor money. - Storage. Databases and JSON have their own number types. In JSON,
System.Text.Jsonreads a number into adecimalwithout passing throughdouble. - Currency.
decimalhas no currency attached. Keep the currency code next to the amount in your own type.
Related
type-decimalandtype-floating-precisionnum-roundandnum-float-comparisonnum-tostring- Tutorial: Math and numbers