Skip to content
Tutorials Center
My learning

Topics

Lesson 14 of 182 ยท Variables and Types

Floating-Point and decimal

Learn C# float, double, decimal and Half - why 0.1 + 0.2 is not 0.3, NaN and Infinity, decimal for money, Math.Round modes and comparing with a tolerance.

Integers are great for counting, but the world is full of fractions: prices, temperatures, distances, percentages. C# gives you several types for numbers with a decimal point, and they behave in surprisingly different ways. Pick the wrong one and a shopping cart totals $19.999999999999996; pick the right one and the problem never appears.

This lesson explains the four types (float, double, decimal and Half), why 0.1 + 0.2 is not exactly 0.3 in two of them, what NaN and Infinity are, how rounding really works in .NET, and the simple rule for deciding which type to use. If you haven't met the whole-number types yet, read Integer Types first.

The floating-point family

A floating-point number stores a value the way scientific notation does: a sign, a string of significant digits, and an exponent that says where the point goes. The point "floats". That design covers a gigantic range (from the size of an atom to the size of the universe) in a fixed number of bytes, at the price of limited precision.

Type Size Approx. precision Range (roughly) Literal suffix
Half 2 bytes 3-4 digits up to ยฑ65,504 (prints as 65500) none (cast)
float 4 bytes 6-9 digits ยฑ3.4 ร— 10^38 f or F
double 8 bytes 15-17 digits ยฑ1.8 ร— 10^308 d or none
decimal 16 bytes 28-29 digits ยฑ7.9 ร— 10^28 m or M

A literal with a decimal point and no suffix, like 3.14, is a double. That default matters: float price = 9.99; does not compile, because you'd be squeezing a double into a smaller type. You write 9.99f for a float and 9.99m for a decimal.

C# The four types side by side

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.

All four print an approximation of one third, but with different numbers of digits. double is the default for scientific, graphics and general-purpose math; float halves the memory and is common in games and GPU work; Half is mostly for machine learning and graphics data where memory bandwidth matters more than accuracy. decimal is a different animal, and we'll get to it.

Why 0.1 + 0.2 is not 0.3

Computers store float and double in binary. Just as one third cannot be written exactly in decimal (0.3333...), the fraction one tenth cannot be written exactly in binary. It becomes an endless repeating pattern that gets cut off after 52 binary digits for a double. So 0.1 is really stored as a number very close to 0.1, and 0.2 likewise. Add two slightly-wrong numbers and the tiny errors show up.

C# The famous 0.1 + 0.2 problem

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.

Since .NET Core 3.0, double.ToString() prints the shortest text that converts back to exactly the same value. That is why 0.1 + 0.2 shows 0.30000000000000004 while the literal 0.3 shows 0.3: they really are two different doubles, one step apart. The F20 format reveals the extra digits behind the scenes.

This is not a C# bug. Java, JavaScript, Python and C++ all behave the same way, because they all use the IEEE 754 standard that your CPU implements in hardware. The lesson: never compare float or double results with == unless you know the values are exact (like whole numbers or powers of two).

Comparing with a tolerance

Compare "close enough" instead. Choose a small epsilon appropriate to your problem and check that the difference is smaller than it:

C# Comparing with a tolerance

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.

Notice that double.Epsilon is not the gap between 1.0 and the next number, as the name suggests to people used to other languages. It is the smallest positive double that exists (about 4.9 ร— 10^-324). Using it as a tolerance for ordinary values is almost the same as using ==. Choose your own epsilon, or use a relative comparison like the one above.

Never use float or double for money. Values like 0.10 cannot be represented exactly, and rounding errors add up across thousands of transactions. Use decimal (next section), or store whole cents in a long.

decimal: exact base-10 arithmetic

decimal stores a 96-bit integer and a scale (a power of ten, 0 to 28). Because it counts in base 10, values like 0.1m and 19.99m are stored exactly, and addition, subtraction and multiplication of decimals give exact results as long as the digits fit. That makes decimal the right type for prices, invoices, tax and anything else where humans expect the numbers to add up the way they do on paper.

C# Money with decimal

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.

Two details to notice. First, 1.5m and 1.50m are equal but print differently; the scale is part of the value, which is handy for showing "2 decimal places" but can surprise you in output. Second, C# refuses to mix decimal with float or double in one expression (error CS0019), forcing you to decide where precision may be lost.

decimal is not magic. 1m / 3m still cannot be written exactly, and it is slower than double (it is done in software, roughly 10 to 50 times slower for arithmetic) and uses 16 bytes. Use it where exactness in base 10 matters, not for physics simulations or graphics.

NaN, Infinity and special values

Floating-point arithmetic never throws for divide-by-zero. Instead it produces special values defined by the IEEE 754 standard:

  • double.PositiveInfinity and double.NegativeInfinity: results like 1.0 / 0.0 or an overflow.
  • double.NaN ("not a number"): results of invalid operations like 0.0 / 0.0 or Math.Sqrt(-1).

NaN has one famous trait: it is not equal to anything, including itself. (The compiler even warns, CS1718, if you write x == x directly, so the demo below compares with a copy.) Use double.IsNaN to test for it. (Interestingly, the Equals method says a NaN equals itself, as the output shows, so that sorting and hash tables keep working. Only the == operator follows the IEEE rule.)

C# NaN and Infinity

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.

Because nan == copy is false, a NaN can silently poison a whole calculation (every operation with it gives NaN) and sneaks past == checks and Contains on lists in confusing ways. If your data can contain NaN, validate it at the boundary with double.IsFinite. Integers and decimal behave the opposite way: they throw DivideByZeroException, because they have no way to represent "infinity".

Rounding

Math.Round has a trap that catches people from other languages. By default it uses banker's rounding (also called round-half-to-even): when a value is exactly halfway between two choices, it rounds to the even neighbor. So 2.5 becomes 2, and 3.5 becomes 4. This avoids a statistical bias over many roundings, but it isn't what school taught you.

You choose the rule with the MidpointRounding enum:

Mode 0.5 1.5 2.5 -2.5 Meaning
ToEven (default) 0 2 2 -2 Halfway goes to the even number
AwayFromZero 1 2 3 -3 The "school" rule
ToZero 0 1 2 -2 Halfway truncates
ToNegativeInfinity 0 1 2 -3 Halfway goes down
ToPositiveInfinity 1 2 3 -2 Halfway goes up
C# Math.Round modes and friends

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.

The 1.005 lines combine both ideas. As a binary double, 1.005 is actually a hair below 1.005, so it is not a midpoint at all and rounds down to 1. As a decimal it really is 1.005, a true midpoint, so the mode decides. With 2.665m the default mode gives 2.66 (the even neighbor) while AwayFromZero gives 2.67. Also note the difference between Floor (toward negative infinity), Ceiling (toward positive infinity) and Truncate (toward zero). Casting a double to int truncates.

For money, round once, at the end of a calculation or at a clear business step, using MidpointRounding.AwayFromZero if that is what your invoices need. Rounding every intermediate result compounds the error.

Choosing the right type

  1. Money, quantities counted in base 10, anything a human audits with a calculator: decimal.
  2. Measurements, science, statistics, geometry, general math: double. This is the default, and the Math class works with it.
  3. Large arrays of numbers where memory or GPU transfer matters (games, graphics, ML): float.
  4. Storing huge numbers of low-precision values: Half.
  5. Whole numbers, even large ones: an integer type, not a floating-point one. A double represents integers exactly only up to 2^53 (9,007,199,254,740,992).
C# Floating-point loses whole numbers too

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.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the type of the literal 3.14?

    A real literal with no suffix is a double. Use f for float and m for decimal. The target variable does not change the literal's type, which is why float x = 3.14; is a compile error.
  2. 2. Why does 0.1 + 0.2 == 0.3 evaluate to false for doubles?

    Binary floating-point cannot represent one tenth exactly, so tiny errors appear. The same happens in Java, Python and JavaScript. Compare with a tolerance, or use decimal.
  3. 3. Which type should you use to store an invoice total?

    decimal stores values like 19.99 exactly in base 10, so sums behave the way people expect. double and float accumulate representation errors.
  4. 4. What does Math.Round(2.5) return with the default settings?

    The default is MidpointRounding.ToEven (banker's rounding): halfway values go to the nearest even number, so 2.5 becomes 2 and 3.5 becomes 4. Pass MidpointRounding.AwayFromZero to get 3.
  5. 5. What happens when you evaluate 1.0 / 0.0 with doubles?

    Floating-point division by zero follows IEEE 754 and gives Infinity (or NaN for 0.0 / 0.0). Only integer and decimal division by zero throw DivideByZeroException.

Summary

  • Real literals are double by default; use f for float and m for decimal.
  • float and double are binary floating-point: fast, wide range, but they cannot store most decimal fractions exactly, so 0.1 + 0.2 != 0.3.
  • Compare floating-point numbers with a tolerance, not ==. double.Epsilon is not a useful tolerance.
  • decimal is exact in base 10 and is the right choice for money, but it is slower and cannot be mixed with double without a cast.
  • Floating-point division by zero gives Infinity or NaN; NaN is not equal to itself, so use double.IsNaN. Integer and decimal division by zero throws.
  • Math.Round rounds halves to even by default; pass MidpointRounding.AwayFromZero for the school rule.
  • double stores whole numbers exactly only up to 2^53.

Next: bool and char