C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Next: This program shows how to specify floats with "f" or "F". It is often preferred to use the uppercase F to reduce confusion.
SuffixC# program that uses float suffixes
using System;
class Program
{
static void Main()
{
float val1 = 1.001f; // Lowercase f suffix.
float val2 = 1.002F; // Uppercase F suffix.
Console.WriteLine(val1);
Console.WriteLine(val2);
}
}
Output
1.001
1.002
Equals: You can use the == equality operator on floats, and other arithmetic operators.
Info: The expression typeof(float) in the program, as well as the GetType method, both return the System.Single type.
Alias: The C# language aliases the float keyword to System.Single so they are precisely equivalent.
Typeof, nameofSingle, DoubleMemory: The memory usage of floats in the C# language is four bytes per float, which is the same as the int type.
Int, uintC# program that tests float type
using System;
class Program
{
static void Main()
{
// Use float type.
float number = 1.5F;
Console.WriteLine(number);
// Set to negative value.
number = -1.001F;
Console.WriteLine(number);
Console.WriteLine(number == -1.001F); // Use == operator
Console.WriteLine(number + 200); // Use + operator
Console.WriteLine(number.GetType());
Console.WriteLine(typeof(float));
Console.WriteLine(float.MinValue.ToString("0"));
Console.WriteLine(float.MaxValue.ToString("0"));
// Find the memory usage for a float value.
long bytes1 = GC.GetTotalMemory(false);
float[] array = new float[1000 * 1000];
array[0] = 1;
long bytes2 = GC.GetTotalMemory(false);
Console.WriteLine("{0} bytes per float", ((bytes2 - bytes1) / (1000000)));
}
}
Output
1.5
-1.001
True
198.999
System.Single
System.Single
-340282300000000000000000000000000000000
340282300000000000000000000000000000000
4 bytes per float
And: The NegativeInfinity and PositiveInfinity constants are tested with float.IsNegativeInfinity and float.IsPositiveInfinity.
C# program that reveals float constants
using System;
class Program
{
static void Main()
{
Console.WriteLine(float.Epsilon);
Console.WriteLine(float.NaN);
Console.WriteLine(float.NegativeInfinity);
Console.WriteLine(float.PositiveInfinity);
}
}
Output
1.401298E-45
NaN
-Infinity
Infinity
And: This can be solved with an epsilon test. The float.Epsilon constant is the smallest possible float value.
So: We take the absolute value of the difference between the two values, and see if the difference is less than float.Epsilon.
Math.AbsHowever: The double type uses more memory than the float type. In a large array this difference becomes relevant.
ArrayTherefore: Using a float instead of a double can be beneficial if you are sure the loss of precision is immaterial.
Also: It is best to match the types closely to existing software to alleviate inconsistencies between different code bases.