C# Floating Point Variables

C# Floating Point Variables

The literal which has an integer part, a decimal part, a fractional part, and an exponent part is known as the floating-point literal. These can be represented either in decimal form or exponential form.

The floating type literal is of double type. f or F can be used as a suffix to specify the value as it cannot be assigned directly to the float variable.

Integers are fine for dealing with whole numbers but of little use when there are numbers after the decimal point. Such numbers may be stored in float or double variable types. The default type for such numbers is double.

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 typePrecisionSize
float~6-9 digits4 bytes
double~15-17 digits8 bytes
decimal28-29 digits16 bytes

 

Floating Point Types

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

Floating-point numbers are positive or negative numbers with one or more decimal points. C# includes three data types for floating-point numbers: float, double, and decimal.

01. Float

Use f or F suffix with literal to make it float type.

For example:

float rate = 5.2F;
float amount = 10_000.5f;
float f1 = 123456.5F;
float f2 = 1.123456f;

 

02. Double

A double data type is used to work with decimals. In this case, the numbers are whole numbers like 10.11, 20.22 or 30.33. In C#, the datatype is denoted by the keyword “Double”.

Use d or D suffix with literal to make it double type.

For example:

double dimension = 3.14d
double radius = 1_000.5D
double d1 = 12345678912345.5d;
double d2 = 1.123456789123456d;

Example 2: 

we will define a double variable called numo. We will then assign a Double value to the variable and then display it accordingly.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace HelloWorld
{
    class Program
    {
        static void Main(string[] args)
        {
            double numo = 40.43;
            Console.WriteLine("Double displayed as expected: " + numo);
            Console.ReadLine();
        }
    }
}

Code Explanation:

  • The double data type is specified to declare a double type variable called num. 
  • The variable is then assigned a value of 40.43.
  • Finally the Console.WriteLine function is used to display the number to the console.

If the above code is entered properly and the program is executed successfully, following output will be displayed.

Output:

C# Floating Point Types - C# Double

From the output, you can clearly see that the double variable called num was displayed in the console.

03. Decimal

The decimal type has more precision and a smaller range than both float and double, and so it is appropriate for financial and monetary calculations.

Use m or M suffix with literal to make it decimal type.

For example:

decimal amount = 9.99m
decimal tax = 0.08M
decimal d1 = 123456789123456789123456789.5m;
decimal d2 = 1.1234567891345679123456789123m;

 

Scientific Notation

Use e or E to indicate the power of 10 as exponent part of scientific notation with float, double or decimal.

For example:

double d = 0.15e2;
Console.WriteLine(d);  // 15;

float f = 123.45e-2f;
Console.WriteLine(f);  // 1.2345

decimal m = 1.2e6m;
Console.WriteLine(m);// 1200000

 

C# Float and Double Special Values

Floating-point types have special values to deal with the results of certain operations.

These special values are:

  • NaN (Not a Number),
  • +Infinity,
  • -Infinity,
  • -0

The float and double types have constants for NaN, +Infinity, and -Infinity.

The constants that represent special values for double and float are as follows:

Special valueDouble constantFloat constant
NaNdouble.NaNfloat.NaN
+Infinitydouble.PositiveInfinityfloat.PositiveInfinity
-Infinitydouble.NegativeInfinityfloat.NegativeInfinity
-0-0.0-0.0f

For example: You can output the value of Negative Infinity in double:

Console.WriteLine (double.NegativeInfinity);  // -Infinity

Rule

  • Dividing a nonzero number by zero results in an infinite value.
  • Dividing zero by zero, or subtracting infinity from infinity, results in a NaN.
  • When using ==, a NaN value is never equal to another value, even another NaN value.
  • To test whether a value is NaN, you must use the float.IsNaN or double.IsNaN method.
  • When using object.Equals, two NaN values are equal.

Demo

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace HelloWorld
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(1.0 / 0.0);                   //  [Infinity] as expected
            Console.WriteLine(-1.0 / 0.0);                  // [-Infinity] as expected
            Console.WriteLine(1.0 / -0.0);                  // [-Infinity] as expected
            Console.WriteLine(-1.0 / -0.0);                 //  [Infinity] as expected
            Console.WriteLine(0.0 / 0.0);                   //  [NaN] as expected
            Console.WriteLine((1.0 / 0.0) - (1.0 / 0.0));   //  [NaN] as expected
            Console.WriteLine(0.0 / 0.0 == double.NaN);     // [False] as expected
            Console.WriteLine(double.IsNaN(0.0 / 0.0));     // [True] as expected
            Console.WriteLine(object.Equals(0.0 / 0.0, double.NaN));   // [True] as expected
            Console.ReadLine();
        }
    }
}

Output:

C# Float and Double Special Values

C# Floating 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 + 0.1;

But it returns false instead:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace HelloWorld
{
    class Program
    {
        static void Main(string[] args)
        {
            bool result = 0.3 == 0.1 + 0.1 + 01;
            Console.WriteLine(result); // false
            Console.ReadLine();
        }
    }
}

Output:

C# Floating equality test

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);

Output:

0.30000000000000004

 

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.

Note

By default, every floating-point literal is of double type and hence we can’t assign directly to float variable. But we can specify floating-point literal as float type by suffixed with f or F. We can specify explicitly floating-point literal as the double type by suffixed with d or D, of course, this convention is not required.