ZetCode

C# floating-point types

last modified November 6, 2026

In this article we work with floating-point numbers in C#. We cover the float, double, decimal, and Half types, show where their precision ends, how to compare and round them, and why money calculations use decimal.

Floating-point numbers represent real numbers with a fixed number of significant digits and an exponent, much like the scientific notation 6.022×10²³. The decimal point floats, which allows very large and very small values in the same type.

Type.NET typeSizeSignificant digitsBaseLiteral
-System.Half2 bytes~32none, cast from double
floatSystem.Single4 bytes~6-921.5f
doubleSystem.Double8 bytes~15-1721.5, 1.5d
decimalSystem.Decimal16 bytes28-29101.5m

The Half, float, and double types are binary floating-point numbers defined by the IEEE 754 standard. Arithmetic on them is done by the processor and is fast. The decimal type stores a 96-bit integer and a power-of-ten scale. It represents decimal fractions such as 0.1 exactly, but its range is much smaller and its arithmetic is slower, because it is done in software.

C# floating-point types overview

The first example declares variables of the four types and prints their sizes and limits.

Program.cs
float f = 1.23456789f;
double d = 1.2345678901234567890;
decimal m = 1.2345678901234567890123456789m;
Half h = (Half)1.23456789;

Console.WriteLine($"Half:    {h}");
Console.WriteLine($"float:   {f}");
Console.WriteLine($"double:  {d}");
Console.WriteLine($"decimal: {m}");
Console.WriteLine();

Console.WriteLine($"float   {sizeof(float),2} bytes, max {float.MaxValue}, epsilon {float.Epsilon}");
Console.WriteLine($"double  {sizeof(double),2} bytes, max {double.MaxValue}, epsilon {double.Epsilon}");
Console.WriteLine($"decimal {sizeof(decimal),2} bytes, max {decimal.MaxValue}");
Console.WriteLine();

double sci = 6.022e23;
float tiny = 1.5e-10f;
decimal price = 19.90m;

Console.WriteLine($"{sci} {tiny} {price}");

We assign values with more digits than the types can hold and see where they are cut off.

float f = 1.23456789f;
double d = 1.2345678901234567890;
decimal m = 1.2345678901234567890123456789m;
Half h = (Half)1.23456789;

A literal without a suffix is a double. The f suffix makes it a float and the m suffix a decimal. Without the suffixes, the assignments would not compile, because the conversion from double may lose information. There is no literal for Half, which is meant for storage and machine learning rather than for calculations.

Console.WriteLine($"float   {sizeof(float),2} bytes, max {float.MaxValue}, epsilon {float.Epsilon}");

Note that float.Epsilon and double.Epsilon are the smallest positive values of the types, not the difference between 1 and the next representable number, as epsilon means in many other languages.

double sci = 6.022e23;
float tiny = 1.5e-10f;
decimal price = 19.90m;

Floating-point literals can use the exponent notation. A decimal keeps its scale, so 19.90m is printed with the trailing zero.

$ dotnet run
Half:    1.234
float:   1.2345679
double:  1.2345678901234567
decimal: 1.2345678901234567890123456789

float    4 bytes, max 3.4028235E+38, epsilon 1E-45
double   8 bytes, max 1.7976931348623157E+308, epsilon 5E-324
decimal 16 bytes, max 79228162514264337593543950335

6.022E+23 1.5E-10 19.90

Precision and representation errors

Binary floating-point types cannot represent most decimal fractions exactly, just as 1/3 cannot be written exactly in decimal digits.

Program.cs
double sum = 0.1 + 0.2;

Console.WriteLine(sum);
Console.WriteLine(sum == 0.3);
Console.WriteLine(0.1.ToString("F20"));
Console.WriteLine();

float fThird = 1f / 3;
double dThird = 1.0 / 3;
decimal mThird = 1m / 3;

Console.WriteLine(fThird);
Console.WriteLine(dThird);
Console.WriteLine(mThird);
Console.WriteLine(mThird * 3);
Console.WriteLine();

double dTotal = 0;
decimal mTotal = 0;

for (int i = 0; i < 1000; i++)
{
    dTotal += 0.1;
    mTotal += 0.1m;
}

Console.WriteLine($"double:  {dTotal}");
Console.WriteLine($"decimal: {mTotal}");
Console.WriteLine();

float big = 16_777_216f;
Console.WriteLine(big + 1f == big);

The example shows several consequences of limited precision.

double sum = 0.1 + 0.2;

Console.WriteLine(sum);
Console.WriteLine(sum == 0.3);
Console.WriteLine(0.1.ToString("F20"));

The closest double to 0.1 is slightly larger than 0.1. The errors of 0.1 and 0.2 add up, and the sum is not the double closest to 0.3. Since .NET Core 3.0, ToString prints the shortest string that round-trips to the same value, so the error is visible. The F20 format shows more digits of the stored value.

float fThird = 1f / 3;
double dThird = 1.0 / 3;
decimal mThird = 1m / 3;

The three types give 8, 16, and 28 digits of 1/3. Not even decimal is exact here: multiplying its result by 3 does not give 1.

for (int i = 0; i < 1000; i++)
{
    dTotal += 0.1;
    mTotal += 0.1m;
}

Small errors accumulate in repeated calculations. After a thousand additions, the double total is visibly off, while the decimal total is exact.

float big = 16_777_216f;
Console.WriteLine(big + 1f == big);

A float has 24 bits of precision. Above 2²⁴, which is 16,777,216, it cannot represent all integers; adding 1 does not change the value.

$ dotnet run
0.30000000000000004
False
0.10000000000000000555

0.33333334
0.3333333333333333
0.3333333333333333333333333333
0.9999999999999999999999999999

double:  99.9999999999986
decimal: 100.0

True

Comparing floating-point values

Because of the representation errors, floating-point results should be compared with a tolerance rather than with the == operator.

Program.cs
double x = 0.1 + 0.2;
double y = 0.3;

Console.WriteLine($"x == y: {x == y}");
Console.WriteLine($"x - y: {x - y}");
Console.WriteLine($"NearlyEqual(x, y): {NearlyEqual(x, y)}");
Console.WriteLine($"NearlyEqual(1e-20, 0): {NearlyEqual(1e-20, 0)}");
Console.WriteLine($"NearlyEqual(1e9 + 0.5, 1e9): {NearlyEqual(1e9 + 0.5, 1e9)}");
Console.WriteLine($"NearlyEqual(1.0, 1.001): {NearlyEqual(1.0, 1.001)}");

static bool NearlyEqual(double a, double b, double relTol = 1e-9, double absTol = 1e-12)
{
    if (a == b) return true;
    if (double.IsNaN(a) || double.IsNaN(b) || double.IsInfinity(a) || double.IsInfinity(b)) return false;

    double diff = Math.Abs(a - b);
    return diff <= absTol || diff <= relTol * Math.Max(Math.Abs(a), Math.Abs(b));
}

The NearlyEqual function combines a relative and an absolute tolerance.

return diff <= absTol || diff <= relTol * Math.Max(Math.Abs(a), Math.Abs(b));

The relative tolerance scales with the magnitude of the numbers: for values around a billion, a difference of 0.5 is negligible. Near zero, a relative tolerance does not work, because any difference is large compared with zero; the absolute tolerance covers this case. The right tolerances depend on the application.

if (double.IsNaN(a) || double.IsNaN(b) || double.IsInfinity(a) || double.IsInfinity(b)) return false;

Special values are handled before the arithmetic. Two equal infinities are already caught by the a == b check.

$ dotnet run
x == y: False
x - y: 5.551115123125783E-17
NearlyEqual(x, y): True
NearlyEqual(1e-20, 0): True
NearlyEqual(1e9 + 0.5, 1e9): True
NearlyEqual(1.0, 1.001): False

Special values

IEEE 754 types have special values for infinity, negative zero, and results that are not a number. The decimal type has none of them and throws exceptions instead.

Program.cs
double posInf = 1.0 / 0;
double negInf = -1.0 / 0;
double nan = 0.0 / 0;
double negZero = -0.0;

Console.WriteLine($"{posInf} {negInf} {nan}");
Console.WriteLine($"nan == double.NaN: {nan == double.NaN}");
Console.WriteLine($"double.IsNaN(nan): {double.IsNaN(nan)}");
Console.WriteLine($"nan.Equals(nan): {nan.Equals(nan)}");
Console.WriteLine($"-0.0 == 0.0: {negZero == 0.0}, 1 / -0.0 = {1 / negZero}");
Console.WriteLine($"double.MaxValue * 2: {double.MaxValue * 2}");
Console.WriteLine($"Math.Sqrt(-1): {Math.Sqrt(-1)}");

double[] vals = [3.0, double.NaN, -1.0, double.PositiveInfinity];
Array.Sort(vals);
Console.WriteLine($"sorted: {string.Join(" ", vals)}");

try
{
    decimal m = decimal.MaxValue;
    m *= 2;
}
catch (OverflowException e)
{
    Console.WriteLine($"decimal: {e.Message}");
}

try
{
    decimal zero = 0m;
    Console.WriteLine(1m / zero);
}
catch (DivideByZeroException e)
{
    Console.WriteLine($"decimal: {e.Message}");
}

Floating-point division by zero does not throw an exception; it produces an infinity or NaN. This is different from integer division.

Console.WriteLine($"nan == double.NaN: {nan == double.NaN}");
Console.WriteLine($"double.IsNaN(nan): {double.IsNaN(nan)}");
Console.WriteLine($"nan.Equals(nan): {nan.Equals(nan)}");

NaN is not equal to anything, including itself, so the == operator cannot detect it. Use double.IsNaN. The Equals method returns true for two NaNs, so that NaN can be found in collections and used as a dictionary key.

Console.WriteLine($"-0.0 == 0.0: {negZero == 0.0}, 1 / -0.0 = {1 / negZero}");

Negative zero equals zero, but it keeps its sign in further calculations.

double[] vals = [3.0, double.NaN, -1.0, double.PositiveInfinity];
Array.Sort(vals);

Sorting puts NaN before all other values.

decimal m = decimal.MaxValue;
m *= 2;

A decimal overflow throws an OverflowException, and division by zero throws a DivideByZeroException.

$ dotnet run
∞ -∞ NaN
nan == double.NaN: False
double.IsNaN(nan): True
nan.Equals(nan): True
-0.0 == 0.0: True, 1 / -0.0 = -∞
double.MaxValue * 2: ∞
Math.Sqrt(-1): NaN
sorted: NaN -1 3 ∞
decimal: Value was either too large or too small for a Decimal.
decimal: Attempted to divide by zero.

Rounding

The Math class rounds numbers in several ways. The rounding of midpoints, values exactly halfway between two results, is controlled by the MidpointRounding enumeration.

Program.cs
double[] vals = [0.5, 1.5, 2.5, -2.5, 2.675];

foreach (double v in vals)
{
    Console.WriteLine($"{v,6}: ToEven {Math.Round(v),3}  AwayFromZero {Math.Round(v, MidpointRounding.AwayFromZero),3}  " +
        $"Floor {Math.Floor(v),3}  Ceiling {Math.Ceiling(v),3}  Truncate {Math.Truncate(v),3}");
}

Console.WriteLine();
Console.WriteLine(Math.Round(2.675, 2));
Console.WriteLine(2.675.ToString("F20"));
Console.WriteLine(Math.Round(2.675m, 2));
Console.WriteLine(Math.Round(2.675m, 2, MidpointRounding.AwayFromZero));
Console.WriteLine();

double pi = Math.PI;
Console.WriteLine($"{pi:F2} {pi:F4} {pi:E3} {pi:G3} {1234567.891:N2}");

We round several values with different methods.

Math.Round(v)

By default, Math.Round uses banker's rounding, MidpointRounding.ToEven: a midpoint is rounded to the nearest even number. Both 1.5 and 2.5 become 2. This avoids the upward bias of always rounding halves up. The rounding taught at school is MidpointRounding.AwayFromZero.

Math.Floor(v)

Math.Floor rounds towards negative infinity, Math.Ceiling towards positive infinity, and Math.Truncate towards zero. They differ for negative numbers.

Console.WriteLine(Math.Round(2.675, 2));
Console.WriteLine(2.675.ToString("F20"));

The stored double is slightly less than 2.675, so it is not really a midpoint. Rounding of such values to decimal places is fragile and may differ between languages and libraries. With decimal, 2.675m is an exact midpoint, and the result follows the chosen rounding mode.

Console.WriteLine($"{pi:F2} {pi:F4} {pi:E3} {pi:G3} {1234567.891:N2}");

When a value only needs to be displayed, a format string is enough. The F format sets the number of decimal places, E uses the exponent notation, G sets the significant digits, and N adds group separators.

$ dotnet run
   0.5: ToEven   0  AwayFromZero   1  Floor   0  Ceiling   1  Truncate   0
   1.5: ToEven   2  AwayFromZero   2  Floor   1  Ceiling   2  Truncate   1
   2.5: ToEven   2  AwayFromZero   3  Floor   2  Ceiling   3  Truncate   2
  -2.5: ToEven  -2  AwayFromZero  -3  Floor  -3  Ceiling  -2  Truncate  -2
 2.675: ToEven   3  AwayFromZero   3  Floor   2  Ceiling   3  Truncate   2

2.68
2.67499999999999982236
2.68
2.68

3.14 3.1416 3.142E+000 3.14 1,234,567.89

Decimal for money

Prices, taxes, and balances are decimal quantities, and the results must match to the cent. The decimal type is the standard choice for them.

Program.cs
using System.Globalization;

var culture = CultureInfo.GetCultureInfo("en-US");

decimal[] items = [19.99m, 5.49m, 3.10m, 12.00m];
decimal subtotal = items.Sum();
decimal tax = decimal.Round(subtotal * 0.0825m, 2, MidpointRounding.AwayFromZero);

Console.WriteLine($"subtotal: {subtotal}");
Console.WriteLine($"tax:      {tax}");
Console.WriteLine(string.Format(culture, "total:    {0:C}", subtotal + tax));
Console.WriteLine();

decimal principal = 1000m;
decimal rate = 0.05m;

decimal balance = principal;
for (int year = 0; year < 10; year++)
{
    balance = decimal.Round(balance * (1 + rate), 2, MidpointRounding.AwayFromZero);
}

double exact = 1000 * Math.Pow(1.05, 10);

Console.WriteLine($"yearly rounded balance: {balance}");
Console.WriteLine($"Math.Pow result:        {exact}");
Console.WriteLine();

decimal share = decimal.Round(100m / 3, 2);
decimal last = 100m - 2 * share;

Console.WriteLine($"split 100 into 3: {share} + {share} + {last} = {share + share + last}");
Console.WriteLine($"scale is kept: {1.10m} {1.10m * 2} {1.1m + 0.00m}");

We compute a bill with tax, a balance with compound interest, and split an amount into three parts.

decimal tax = decimal.Round(subtotal * 0.0825m, 2, MidpointRounding.AwayFromZero);

The tax is rounded to cents explicitly, with the rounding mode required by the business rules.

Console.WriteLine(string.Format(culture, "total:    {0:C}", subtotal + tax));

The C currency format depends on the culture, so we pass the culture explicitly.

for (int year = 0; year < 10; year++)
{
    balance = decimal.Round(balance * (1 + rate), 2, MidpointRounding.AwayFromZero);
}

A bank credits the interest in whole cents every year. The rounded balance differs from the mathematical result computed with Math.Pow, which has no decimal overload.

decimal share = decimal.Round(100m / 3, 2);
decimal last = 100m - 2 * share;

An amount that cannot be split evenly is rounded, and the remainder is added to the last part, so the parts add up to the original amount.

Console.WriteLine($"scale is kept: {1.10m} {1.10m * 2} {1.1m + 0.00m}");

A decimal remembers the number of decimal places. The results of addition and multiplication keep the scale, which is useful for amounts.

$ dotnet run
subtotal: 40.58
tax:      3.35
total:    $43.93

yearly rounded balance: 1628.91
Math.Pow result:        1628.894626777442

split 100 into 3: 33.33 + 33.33 + 33.34 = 100.00
scale is kept: 1.10 2.20 1.10

Choosing a type

Source

Floating-point numeric types

In this article we have worked with floating-point types in C#.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all C# tutorials.