skip to content

In a C# invoicing service, why should line totals and tax be decimal rather than double, and what can decimal still get wrong?

level: middleimportance: must knowfreq 78%

answer

  1. base 2 versus base 10 fractions
  2. the m suffix on literals
  3. no implicit conversion between the two
  4. one third is still rounded

basics

~20 s

decimal stores a base-10 scaled integer, so 0.10 and 0.20 add to exactly 0.30, while double's binary fractions cannot represent 0.1. decimal still rounds non-terminating results like 1m / 3m, and costs 16 bytes and software arithmetic.

solid answer

~50 s

`double` is IEEE 754 binary floating point, so amounts such as `0.1` are stored as the nearest binary fraction and sums drift: `0.1 + 0.2 == 0.3` is `false`. `decimal` stores a 96-bit integer and a power-of-ten scale from 0 to 28, so any amount whose digits fit that significand (28-29 significant digits) is exact and `0.1m + 0.2m == 0.3m` is `true`. The compiler keeps the two apart: `decimal price = 19.99;` fails with CS0664 because a literal needs the `m` suffix, and `19.99m * 0.0825` fails with CS0019 because neither type converts implicitly to the other. decimal is not magic: `1m / 3m * 3` is `0.9999999999999999999999999999`, so rounding rules are still yours. It also throws on overflow and division by zero, has no NaN or infinity, takes 16 bytes and is slower.

code

csharp · 22 lines
csharp
decimal[] lines = { 0.10m, 0.20m };
double[] linesAsDouble = { 0.10, 0.20 };

Console.WriteLine(lines.Sum() == 0.30m);           // True: 0.1 and 0.2 are exact in base 10
Console.WriteLine(linesAsDouble.Sum() == 0.30);    // False: the double sum is 0.30000000000000004

decimal third = 1m / 3m;
Console.WriteLine(third * 3);                      // 0.9999999999999999999999999999
Console.WriteLine(1.10m);                          // 1.10: the scale (trailing zero) is kept

// decimal price = 19.99;        // CS0664: a double literal needs the m suffix
// var mixed = 19.99m * 0.0825;  // CS0019: no implicit conversion between double and decimal

decimal ledgerTotal = decimal.MaxValue;
try
{
    ledgerTotal = unchecked(ledgerTotal + 1m);
}
catch (OverflowException)
{
    Console.WriteLine("OverflowException");        // decimal overflow throws even in unchecked
}

go deeper

for a junior

Recall that money uses decimal with the m suffix, and that 0.1 + 0.2 == 0.3 is false for double but true for decimal.

for a middle

Explain binary versus base-10 representation, the compiler errors that keep decimal and double apart, and why 1m / 3m * 3 is still not 1.

for a senior

Show where a double leaked into a money path, how the loud failures of decimal help, and where rounding to cents must still be explicit.

for a principal

Frame decimal versus double as a domain decision for the codebase: exact audited quantities versus measurements, and where conversions may happen.

## Two different kinds of fraction C# has three floating-point types, and they split into two families: | Type | Representation | Precision | Size | Special values | |---|---|---|---|---| | `float` (`System.Single`) | binary, IEEE 754 | about 6-9 digits | 4 bytes | NaN, infinities | | `double` (`System.Double`) | binary, IEEE 754 | about 15-17 digits | 8 bytes | NaN, infinities | | `decimal` (`System.Decimal`) | 96-bit integer and a base-10 scale | 28-29 digits | 16 bytes | none | A **binary** floating-point number can only represent fractions whose denominator is a power of two. One tenth is not one of them, so the literal `0.1` is stored as the nearest binary value, slightly off. Each addition rounds again, which is why `0.1 + 0.2` is `0.30000000000000004` and adding `0.1` ten times does not give exactly `1.0`. A **decimal** value is an integer significand divided by a power of ten between 0 and 28. The runtime source describes it as "ideally suited to financial calculations". Any amount whose digits fit the 96-bit significand, 28-29 significant digits with at most 28 after the point, is stored exactly, so cents, basis points and tax rates like `0.0825m` cost no representation error. ## What the compiler enforces C# deliberately keeps `decimal` and the binary types apart: - A real literal without a suffix is a `double`. `decimal price = 19.99;` fails with CS0664, "Literal of type double cannot be implicitly converted to type 'decimal'; use an 'M' suffix to create a literal of this type". Write `19.99m`. - There is no implicit conversion between `decimal` and `double` in either direction, so `19.99m * 0.0825` fails with CS0019, "Operator '*' cannot be applied to operands of type 'decimal' and 'double'". You must cast one side explicitly, which makes every crossing visible in review. - Integral types convert implicitly to `decimal`, so `quantity * unitPrice` with an `int` quantity just works. ## What decimal still gets wrong decimal removes **representation** error for base-10 amounts; it does not remove **rounding**: 1. Results that do not terminate in base 10 are rounded at 28-29 significant digits: `1m / 3m` is `0.3333333333333333333333333333`, and multiplying by `3` gives `0.9999999999999999999999999999`, not `1`. 2. Tax and currency conversion produce more decimal places than the currency allows, so the code must still round to cents with an explicit `Math.Round` mode. 3. Splitting an amount into parts leaves a remainder that someone must receive. ## Behaviour differences beyond precision - **No NaN or infinity**: decimal division by zero throws `DivideByZeroException`, and overflow throws `OverflowException` in both checked and unchecked contexts. A bug fails loudly instead of flowing NaN into a report. - **Scale is preserved**: `1.10m` prints `1.10` while `1.1m` prints `1.1`, and the two compare equal with `==` and `Equals`. - **Converting from double** throws `OverflowException` for NaN, infinity or out-of-range values. - **Cost**: 16 bytes instead of 8, and arithmetic implemented in software rather than by the floating-point hardware. For an invoicing service that is negligible; for millions of values in a numeric kernel it is not. ## When double is still right Measurements, physics, statistics, graphics and machine learning work on values that are approximations to begin with. There, `double` is the right type: faster, smaller, with the full `Math` library (`Math.Sqrt` and friends take `double`) and NaN to mark missing data. The rule of thumb is about the **domain**: if the value is an exact count of decimal units that people add up and audit, use `decimal`; if it is a measurement, use `double`. ## In the invoicing service Review a money path for these signs that `double` has leaked in: - a literal without the `m` suffix assigned through an explicit `(decimal)` cast; - a `double` field or parameter named `price`, `amount` or `total`; - comparisons with a tolerance such as `Math.Abs(a - b) < 0.0001`, which only `double` needs. Keep line totals, discounts and tax in `decimal`, write literals with `m`, round each tax amount to the currency's places with an explicit midpoint rule, and convert to `double` only at the edge where a chart or a statistics library needs it.

  • Why does `decimal price = 19.99;` not compile in C#, when `decimal quantity = 3;` does?
    `19.99` is a `double` literal, and C# has no implicit conversion from `double` to `decimal`, because the conversion can lose precision or throw (for NaN, infinity or out-of-range values), so it must be written as an explicit cast. The compiler reports CS0664 and suggests the `m` suffix. `3` is an `int` literal, and every integral type converts implicitly and exactly to `decimal`.
  • Do 1.10m and 1.1m compare equal in C#, and what differs between them?
    They are equal: `==`, `Equals` and `GetHashCode` treat them as the same number, so they behave as one dictionary key. What differs is the stored scale, 2 versus 1, so `ToString()` prints `1.10` and `1.1`. Arithmetic keeps scales as well, which is why a sum of two-place amounts prints with two places.
  • When is double still the right numeric type in a C# codebase?
    When the values are measurements or approximations: sensor readings, durations in seconds, physics, statistics, graphics, ML features. There, the extra speed and smaller size matter, `Math.Sqrt` and similar functions take `double`, and NaN can mark missing data. Use `decimal` when the values are exact decimal quantities people sum and audit, such as money.

double is a ruler marked in halves, quarters, eighths and so on: it can get very close to 0.1 but has no mark exactly there. decimal is a ruler marked in tenths, hundredths and thousandths, so every cent has its own mark, yet a third of a dollar still falls between two marks and must be rounded.

  • double is fine for money because it holds 15 significant digits.
  • decimal is exact, so financial code never needs to round.
  • decimal and double convert implicitly, so mixing them is harmless.
  • Dividing a decimal by zero returns infinity like double does.
  • 1.10m and 1.1m are different keys in a Dictionary<decimal, T>.