See Also: Single Members
The float value type represents a single-precision 32-bit number with values ranging from negative 3.402823e38 to positive 3.402823e38, as well as positive or negative zero, float.PositiveInfinity, float.NegativeInfinity, and not a number (float.NaN). It is intended to represent values that are extremely large (such as distances between planets or galaxies) or extremely small (such as the molecular mass of a substance in kilograms) and that often are imprecise (such as the distance from earth to another solar system). The float type complies with the IEC 60559:1989 (IEEE 754) standard for binary floating-point arithmetic.
This topic consists of the following sections:
float provides methods to compare instances of this type, to convert the value of an instance to its string representation, and to convert the string representation of a number to an instance of this type. For information about how format specification codes control the string representation of value types, see Formatting Types, Standard Numeric Format Strings, and Custom Numeric Format Strings.
The float data type stores single-precision floating-point values in a 32-bit binary format, as shown in the following table:
Significand or mantissa |
0-22 |
Exponent |
23-30 |
Sign (0 = positive, 1 = negative) |
31 |
Just as decimal fractions are unable to precisely represent some fractional values (such as 1/3 or Math.PI), binary fractions are unable to represent some fractional values. For example, 2/10, which is represented precisely by .2 as a decimal fraction, is represented by .0011111001001100 as a binary fraction, with the pattern "1100" repeating to infinity. In this case, the floating-point value provides an imprecise representation of the number that it represents. Performing additional mathematical operations on the original floating-point value often increases its lack of precision. For example, if you compare the results of multiplying .3 by 10 and adding .3 to .3 nine times, you will see that addition produces the less precise result, because it involves eight more operations than multiplication. Note that this disparity is apparent only if you display the two float values by using the "R" standard numeric format string, which, if necessary, displays all 9 digits of precision supported by the float type.
code reference: System.Single.Structure#3
Because some numbers cannot be represented exactly as fractional binary values, floating-point numbers can only approximate real numbers.
All floating-point numbers have a limited number of significant digits, which also determines how accurately a floating-point value approximates a real number. A float value has up to 7 decimal digits of precision, although a maximum of 9 digits is maintained internally. This means that some floating-point operations may lack the precision to change a floating-point value. The following example defines a large single-precision floating-point value, and then adds the product of float.Epsilon and one quadrillion to it. However, the product is too small to modify the original floating-point value. Its least significant digit is thousandths, whereas the most significant digit in the product is 1.
code reference: System.Single.Structure#4
The limited precision of a floating-point number has several consequences:
Two floating-point numbers that appear equal for a particular precision might not compare equal because their least significant digits are different. In the following example, a series of numbers are added together, and their total is compared with their expected total. Although the two values appear to be the same, a call to the Equals method indicates that they are not.
code reference: System.Single.Structure#6
If you change the format items in the Console.WriteLine(string, object, object) statement from {0} and {1} to {0:R} and {1:R} to display all significant digits of the two float values, it is clear that the two values are unequal because of a loss of precision during the addition operations. In this case, the issue can be resolved by calling the Math.Round(double, int) method to round the float values to the desired precision before performing the comparison.
A mathematical or comparison operation that uses a floating-point number might not yield the same result if a decimal number is used, because the binary floating-point number might not equal the decimal number. A previous example illustrated this by displaying the result of multiplying .3 by 10 and adding .3 to .3 nine times.
When accuracy in numeric operations with fractional values is important, use the decimal type instead of the float type. When accuracy in numeric operations with integral values beyond the range of the long or ulong types is important, use the System.Numerics.BigInteger type.
A value might not round-trip if a floating-point number is involved. A value is said to round-trip if an operation converts an original floating-point number to another form, an inverse operation transforms the converted form back to a floating-point number, and the final floating-point number is not equal to the original floating-point number. The round trip might fail because one or more least significant digits are lost or changed in a conversion. In the following example, three float values are converted to strings and saved in a file. As the output shows, although the values appear to be identical, the restored values are not equal to the original values.
code reference: System.Single.Structure#7
In this case, the values can be successfully round-tripped by using the "R" standard numeric format string to preserve the full precision of float values, as the following example shows.
code reference: System.Single.Structure#8
float values have less precision than double values. A float value that is converted to a seemingly equivalent double often does not equal the double value because of differences in precision. In the following example, the result of identical division operations is assigned to a double value and a float value. After the float value is cast to a double, a comparison of the two values shows that they are unequal.
code reference: System.Double.Structure#5
To avoid this problem, either use the double data type in place of the float data type, or use the Math.Round(double) method so that both values have the same precision.
To be considered equal, two float values must represent identical values. However, because of differences in precision between values, or because of a loss of precision by one or both values, floating-point values that are expected to be identical often turn out to be unequal due to differences in their least significant digits. As a result, calls to the float.Equals(float) method to determine whether two values are equal, or calls to the float.CompareTo(float) method to determine the relationship between two float values, often yield unexpected results. This is evident in the following example, where two apparently equal float values turn out to be unequal, because the first value has 7 digits of precision, whereas the second value has 9.
code reference: System.Single.Structure#9
Calculated values that follow different code paths and that are manipulated in different ways often prove to be unequal. In the following example, one float value is squared, and then the square root is calculated to restore the original value. A second float is multiplied by 3.51 and squared before the square root of the result is divided by 3.51 to restore the original value. Although the two values appear to be identical, a call to the float.Equals(float) method indicates that they are not equal. Using the "R" standard format string to return a result string that displays all the significant digits of each float value shows that the second value is .0000000000001 less than the first.
code reference: System.Single.Structure#10
In cases where a loss of precision is likely to affect the result of a comparison, you can use the following techniques instead of calling the float.Equals(float) or float.CompareTo(float) method:
Call the Math.Round(double) method to ensure that both values have the same precision. The following example modifies a previous example to use this approach so that two fractional values are equivalent.
code reference: System.Single.Structure#11
Note that the problem of precision still applies to rounding of midpoint values. For more information, see the Math.Round(double, int, MidpointRounding) method.
Test for approximate equality instead of equality. This technique requires that you define either an absolute amount by which the two values can differ but still be equal, or that you define a relative amount by which the smaller value can diverge from the larger value.
The following example uses the latter approach to define an IsApproximatelyEqual method that tests the relative difference between two values. It also contrasts the result of calls to the IsApproximatelyEqual method and the float.Equals(float) method.
code reference: System.Single.Structure#12
Operations with floating-point values do not throw exceptions, unlike operations with integral types, which throw exceptions in cases of illegal operations such as division by zero or overflow. Instead, in these situations, the result of a floating-point operation is zero, positive infinity, negative infinity, or not a number (NaN):
If the result of a floating-point operation is too small for the destination format, the result is zero. This can occur when two very small floating-point numbers are multiplied, as the following example shows.
code reference: System.Single.Structure#1
If the magnitude of the result of a floating-point operation exceeds the range of the destination format, the result of the operation is float.PositiveInfinity or float.NegativeInfinity, as appropriate for the sign of the result. The result of an operation that overflows float.MaxValue is float.PositiveInfinity, and the result of an operation that overflows float.MinValue is float.NegativeInfinity, as the following example shows.
code reference: System.Single.Structure#2
float.PositiveInfinity also results from a division by zero with a positive dividend, and float.NegativeInfinity results from a division by zero with a negative dividend.
If a floating-point operation is invalid, the result of the operation is float.NaN. For example, float.NaN results from the following operations:
The float structure and related types provide methods to perform the following categories of operations:
Comparison of values. You can call the float.Equals(float) method to determine whether two float values are equal, or the float.CompareTo(float) method to determine the relationship between two values.
The float structure also supports a complete set of comparison operators. For example, you can test for equality or inequality, or determine whether one value is greater than or equal to another value. If one of the operands is a double, the float value is converted to a double before performing the comparison. If one of the operands is an integral type, it is converted to a float before performing the comparison. Although these are widening conversions, they may involve a loss of precision.
You can also call the float.IsNaN(float), float.IsInfinity(float), float.IsPositiveInfinity(float), and float.IsNegativeInfinity(float) methods to test for these special values.
Mathematical operations. Common arithmetic operations such as addition, subtraction, multiplication, and division are implemented by language compilers and Common Intermediate Language (CIL) instructions rather than by float methods. If the other operand in a mathematical operation is a double, the float is converted to a double before performing the operation, and the result of the operation is also a double value. If the other operand is an integral type, it is converted to a float before performing the operation, and the result of the operation is also a float value.
You can perform other mathematical operations by calling static (Shared in Visual Basic) methods in the Math class. These include additional methods commonly used for arithmetic (such as Math.Abs(double), Math.Sign(double), and Math.Sqrt(double)), geometry (such as Math.Cos(double) and Math.Sin(double)), and calculus (such as Math.Log(double)). In all cases, the float value is converted to a double.
You can also manipulate the individual bits in a float value. The BitConverter.GetBytes(float) method returns its bit pattern in a byte array. By passing that byte array to the BitConverter.ToInt32(Byte[], int) method, you can also preserve the float value's bit pattern in a 32-bit integer.
Rounding. Rounding is often used as a technique for reducing the impact of differences between values caused by problems of floating-point representation and precision. You can round a float value by calling the Math.Round(double) method. However, note that the float value is converted to a double before the method is called, and the conversion can involve a loss of precision.
Formatting. You can convert a float value to its string representation by calling the float.ToString method or by using the composite formatting feature. For information about how format strings control the string representation of floating-point values, see the Standard Numeric Format Strings and Custom Numeric Format Strings topics.
Parsing strings. You can convert the string representation of a floating-point value to a float value by calling the float.Parse(string) or float.TryParse(string, Single@) method. If the parse operation fails, the float.Parse(string) method throws an exception, whereas the float.TryParse(string, Single@) method returns false.
Type conversion. The float structure provides an explicit interface implementation for the IConvertible interface, which supports conversion between any two standard .NET Framework data types. Language compilers also support the implicit conversion of values for all other standard numeric types except for the conversion of double to float values. Conversion of a value of any standard numeric type other than a double to a float is a widening conversion and does not require the use of a casting operator or conversion method.
However, conversion of 32-bit and 64-bit integer values can involve a loss of precision. The following table lists the differences in precision for 32-bit, 64-bit, and double types:
The problem of precision most frequently affects float values that are converted to double values. In the following example, two values produced by identical division operations are unequal, because one of the values is a single-precision floating point value that is converted to a double.
code reference: System.Single.Structure#5