C# float

Summary: in this tutorial, you’ll learn how to use the C# float types to represent floating-point numbers.

Introduction to the C# float types

To represent real numbers, C# uses the following floating number types: float, double and decimal. The following table shows the characteristics of the floating-point types:

Float typeApproximate rangePrecisionSize
float±1.5 x 10−45 to ±3.4 x 1038~6-9 digits4 bytes
double±5.0 × 10−324 to ±1.7 × 10308~15-17 digits8 bytes
decimal±1.0 x 10-28 to ±7.9228 x 102828-29 digits16 bytes

Equality test

Since computers only can store the floating-point numbers approximately, it’ll cause unexpected behavior if you attempt to compare two float numbers.

For example, the following expression should return true:

0.3 == 0.1 + 0.1 + 01;Code language: C# (cs)

But it returns false instead:

bool result = 0.3 == 0.1 + 0.1 + 01;
Console.WriteLine(result); // falseCode language: C# (cs)

The reason is that the expression returns a value that is approximately equal to 0.3, not 0.3. See the following:

Console.WriteLine(0.1 + 0.1 + 0.1);Code language: C# (cs)

Output:

0.30000000000000004Code language: C# (cs)

Float literals

Each float type has a specific literal form. And all float literals can have the digit separator (_) to make them more readable.

float

The float literals have the f or F suffix. For example:

float rate = 5.2F;
float amount = 10_000.5f;Code language: C# (cs)

double

The double literals have no suffix. For example:

double dimension = 3.14
double radius = 1_000.5Code language: C# (cs)

Or with the d or D suffix like this:

double dimension = 3.14d
double radius = 1_000.5DCode language: C# (cs)

decimal

The decimal literals have m or M suffix:

decimal amount = 9.99m
decimal tax = 0.08MCode language: C# (cs)

Conversions

C# implicitly converts a value of float to double. However, you can use an explicit cast to convert a value from one floating-point type to another.

Summary

  • C# uses the float, double, and demical types to represent real numbers.
  • Avoid using the equality operator == to compare two real numbers.
Was this tutorial helpful ?