# Single Structure

**.NET Framework 4.6 and 4.5**

Represents a single-precision floating-point number.

**Namespace:**System

**Assembly:**mscorlib (in mscorlib.dll)

The Single type exposes the following members.

Name | Description | |
---|---|---|

CompareTo(Object) | Compares this instance to a specified object and returns an integer that indicates whether the value of this instance is less than, equal to, or greater than the value of the specified object. | |

CompareTo(Single) | Compares this instance to a specified single-precision floating-point number and returns an integer that indicates whether the value of this instance is less than, equal to, or greater than the value of the specified single-precision floating-point number. | |

Equals(Object) | Returns a value indicating whether this instance is equal to a specified object. (Overrides ValueType.Equals(Object).) | |

Equals(Single) | Returns a value indicating whether this instance and a specified Single object represent the same value. | |

GetHashCode | Returns the hash code for this instance. (Overrides ValueType.GetHashCode().) | |

GetType | Gets the Type of the current instance. (Inherited from Object.) | |

GetTypeCode | Returns the TypeCode for value type Single. | |

IsInfinity | Returns a value indicating whether the specified number evaluates to negative or positive infinity. | |

IsNaN | Returns a value that indicates whether the specified value is not a number (NaN). | |

IsNegativeInfinity | Returns a value indicating whether the specified number evaluates to negative infinity. | |

IsPositiveInfinity | Returns a value indicating whether the specified number evaluates to positive infinity. | |

Parse(String) | Converts the string representation of a number to its single-precision floating-point number equivalent. | |

Parse(String, NumberStyles) | Converts the string representation of a number in a specified style to its single-precision floating-point number equivalent. | |

Parse(String, IFormatProvider) | Converts the string representation of a number in a specified culture-specific format to its single-precision floating-point number equivalent. | |

Parse(String, NumberStyles, IFormatProvider) | Converts the string representation of a number in a specified style and culture-specific format to its single-precision floating-point number equivalent. | |

ToString() | Converts the numeric value of this instance to its equivalent string representation. (Overrides ValueType.ToString().) | |

ToString(IFormatProvider) | Converts the numeric value of this instance to its equivalent string representation using the specified culture-specific format information. | |

ToString(String) | Converts the numeric value of this instance to its equivalent string representation, using the specified format. | |

ToString(String, IFormatProvider) | Converts the numeric value of this instance to its equivalent string representation using the specified format and culture-specific format information. | |

TryParse(String, Single) | Converts the string representation of a number to its single-precision floating-point number equivalent. A return value indicates whether the conversion succeeded or failed. | |

TryParse(String, NumberStyles, IFormatProvider, Single) | Converts the string representation of a number in a specified style and culture-specific format to its single-precision floating-point number equivalent. A return value indicates whether the conversion succeeded or failed. |

Name | Description | |
---|---|---|

Equality | Returns a value that indicates whether two specified Single values are equal. | |

GreaterThan | Returns a value that indicates whether a specified Single value is greater than another specified Single value. | |

GreaterThanOrEqual | Returns a value that indicates whether a specified Single value is greater than or equal to another specified Single value. | |

Inequality | Returns a value that indicates whether two specified Single values are not equal. | |

LessThan | Returns a value that indicates whether a specified Single value is less than another specified Single value. | |

LessThanOrEqual | Returns a value that indicates whether a specified Single value is less than or equal to another specified Single value. |

Name | Description | |
---|---|---|

Epsilon | Represents the smallest positive Single value that is greater than zero. This field is constant. | |

MaxValue | Represents the largest possible value of Single. This field is constant. | |

MinValue | Represents the smallest possible value of Single. This field is constant. | |

NaN | Represents not a number (NaN). This field is constant. | |

NegativeInfinity | Represents negative infinity. This field is constant. | |

PositiveInfinity | Represents positive infinity. This field is constant. |

Name | Description | |
---|---|---|

IComparable.CompareTo | Compares the current instance with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other object. | |

IConvertible.ToBoolean | Infrastructure. For a description of this member, see IConvertible.ToBoolean. | |

IConvertible.ToByte | Infrastructure. For a description of this member, see IConvertible.ToByte. | |

IConvertible.ToChar | Infrastructure. This conversion is not supported. Attempting to use this method throws an InvalidCastException. | |

IConvertible.ToDateTime | Infrastructure. This conversion is not supported. Attempting to use this method throws an InvalidCastException. | |

IConvertible.ToDecimal | Infrastructure. For a description of this member, see IConvertible.ToDecimal. | |

IConvertible.ToDouble | Infrastructure. For a description of this member, see IConvertible.ToDouble. | |

IConvertible.ToInt16 | Infrastructure. For a description of this member, see IConvertible.ToInt16. | |

IConvertible.ToInt32 | Infrastructure. For a description of this member, see IConvertible.ToInt32. | |

IConvertible.ToInt64 | Infrastructure. For a description of this member, see IConvertible.ToInt64. | |

IConvertible.ToSByte | Infrastructure. For a description of this member, see IConvertible.ToSByte. | |

IConvertible.ToSingle | Infrastructure. For a description of this member, see IConvertible.ToSingle. | |

IConvertible.ToType | Infrastructure. For a description of this member, see IConvertible.ToType. | |

IConvertible.ToUInt16 | Infrastructure. For a description of this member, see IConvertible.ToUInt16. | |

IConvertible.ToUInt32 | Infrastructure. For a description of this member, see IConvertible.ToUInt32. | |

IConvertible.ToUInt64 | Infrastructure. For a description of this member, see IConvertible.ToUInt64. |

The Single 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, PositiveInfinity, NegativeInfinity, and not a number (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 Single type complies with the IEC 60559:1989 (IEEE 754) standard for binary floating-point arithmetic.

This topic consists of the following sections:

System.Single 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 in the .NET Framework, Standard Numeric Format Strings, and Custom Numeric Format Strings.

### Floating-point representation and precision

The Single data type stores single-precision floating-point values in a 32-bit binary format, as shown in the following table:

Part | Bits |
---|---|

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 Single values by using the "R" standard numeric format string, which, if necessary, displays all 9 digits of precision supported by the Single type.

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 Single 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 Single.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-312.

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.

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 Single 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, Int32) method to round the Single 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 Single type. When accuracy in numeric operations with integral values beyond the range of the Int64 or UInt64 types is important, use the 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 Single 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.

Imports System.IO Module Example Public Sub Main() Dim sw As New StreamWriter(".\Singles.dat") Dim values() As Single = { 3.2/1.11, 1.0/3, CSng(Math.PI) } For ctr As Integer = 0 To values.Length - 1 sw.Write(values(ctr).ToString()) If ctr <> values.Length - 1 Then sw.Write("|") Next sw.Close() Dim restoredValues(values.Length - 1) As Single Dim sr As New StreamReader(".\Singles.dat") Dim temp As String = sr.ReadToEnd() Dim tempStrings() As String = temp.Split("|"c) For ctr As Integer = 0 To tempStrings.Length - 1 restoredValues(ctr) = Single.Parse(tempStrings(ctr)) Next For ctr As Integer = 0 To values.Length - 1 Console.WriteLine("{0} {2} {1}", values(ctr), restoredValues(ctr), If(values(ctr).Equals(restoredValues(ctr)), "=", "<>")) Next End Sub End Module ' The example displays the following output: ' 2.882883 <> 2.882883 ' 0.3333333 <> 0.3333333 ' 3.141593 <> 3.141593

using System; using System.IO; public class Example { public static void Main() { StreamWriter sw = new StreamWriter(@".\Singles.dat"); Single[] values = { 3.2f/1.11f, 1.0f/3f, (float) Math.PI }; for (int ctr = 0; ctr < values.Length; ctr++) sw.Write("{0:R}{1}", values[ctr], ctr < values.Length - 1 ? "|" : "" ); sw.Close(); Single[] restoredValues = new Single[values.Length]; StreamReader sr = new StreamReader(@".\Singles.dat"); string temp = sr.ReadToEnd(); string[] tempStrings = temp.Split('|'); for (int ctr = 0; ctr < tempStrings.Length; ctr++) restoredValues[ctr] = Single.Parse(tempStrings[ctr]); for (int ctr = 0; ctr < values.Length; ctr++) Console.WriteLine("{0} {2} {1}", values[ctr], restoredValues[ctr], values[ctr].Equals(restoredValues[ctr]) ? "=" : "<>"); } } // The example displays the following output: // 2.882883 = 2.882883 // 0.3333333 = 0.3333333 // 3.141593 = 3.141593

In this case, the values can be successfully round-tripped by using the "R" standard numeric format string to preserve the full precision of Single values, as the following example shows.

Single values have less precision than Double values. A Single 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 Single value. After the Single value is cast to a Double, a comparison of the two values shows that they are unequal.

To avoid this problem, either use the Double data type in place of the Single data type, or use the Round method so that both values have the same precision.

### Testing for equality

To be considered equal, two Single 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 Equals method to determine whether two values are equal, or calls to the CompareTo method to determine the relationship between two Single values, often yield unexpected results. This is evident in the following example, where two apparently equal Single values turn out to be unequal, because the first value has 7 digits of precision, whereas the second value has 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 Single value is squared, and then the square root is calculated to restore the original value. A second Single 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 Equals(Single) 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 Single value shows that the second value is .0000000000001 less than the first.

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 Equals or CompareTo method:

Call the Math.Round 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.

Note that the problem of precision still applies to rounding of midpoint values. For more information, see the Math.Round(Double, Int32, 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.

**Caution**Single.Epsilon is sometimes used as an absolute measure of the distance between two Single values when testing for equality. However, Single.Epsilon measures the smallest possible value that can be added to, or subtracted from, a Single whose value is zero. For most positive and negative Single values, the value of Single.Epsilon is too small to be detected. Therefore, except for values that are zero, we do not recommend its use in tests for equality.

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 Equals(Single) method.

### Floating-point values and exceptions

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.

If the magnitude of the result of a floating-point operation exceeds the range of the destination format, the result of the operation is PositiveInfinity or NegativeInfinity, as appropriate for the sign of the result. The result of an operation that overflows Single.MaxValue is PositiveInfinity, and the result of an operation that overflows Single.MinValue is NegativeInfinity, as the following example shows.

PositiveInfinity also results from a division by zero with a positive dividend, and NegativeInfinity results from a division by zero with a negative dividend.

If a floating-point operation is invalid, the result of the operation is NaN. For example, NaN results from the following operations:

Division by zero with a dividend of zero. Note that other cases of division by zero result in either PositiveInfinity or NegativeInfinity.

Any floating-point operation with invalid input. For example, attempting to find the square root of a negative value returns NaN.

Any operation with an argument whose value is Single.NaN.

### Type conversions and the Single structure

The Single structure does not define any explicit or implicit conversion operators; instead, conversions are implemented by the compiler.

The following table lists the possible conversions of a value of the other primitive numeric types to a Single value, It also indicates whether the conversion is widening or narrowing and whether the resulting Single may have less precision than the original value.

Conversion from | Widening/narrowing | Possible loss of precision |
---|---|---|

Widening | No | |

Widening Note that C# requires a cast operator. | Yes. Decimal supports 29 decimal digits of precision; Single supports 9. | |

Narrowing; out-of-range values are converted to Double.NegativeInfinity or Double.PositiveInfinity. | Yes. Double supports 17 decimal digits of precision; Single supports 9. | |

Widening | No | |

Widening | Yes. Int32 supports 10 decimal digits of precision; Single supports 9. | |

Widening | Yes. Int64 supports 19 decimal digits of precision; Single supports 9. | |

Widening | No | |

Widening | No | |

Widening | Yes. UInt32 supports 10 decimal digits of precision; Single supports 9. | |

Widening | Yes. Int64 supports 20 decimal digits of precision; Single supports 9. |

The following example converts the minimum or maximum value of other primitive numeric types to a Single value.

In addition, the Double values Double.NaN, Double.PositiveInfinity, and Double.NegativeInfinity covert to Single.NaN, Single.PositiveInfinity, and Single.NegativeInfinity, respectively.

Note that the conversion of the value of some numeric types to a Single value can involve a loss of precision. As the example illustrates, a loss of precision is possible when converting Decimal, Double, Int32, Int64, UInt32, and UInt64 values to Single values.

The conversion of a Single value to a Double is a widening conversion. The conversion may result in a loss of precision if the Double type does not have a precise representation for the Single value.

The conversion of a Single value to a value of any primitive numeric data type other than a Double is a narrowing conversion and requires a cast operator (in C#) or a conversion method (in Visual Basic). Values that are outside the range of the target data type, which are defined by the target type's MinValue and MaxValue properties, behave as shown in the following table.

Target type | Result |
---|---|

Any integral type | An OverflowException exception if the conversion occurs in a checked context. If the conversion occurs in an unchecked context (the default in C#), the conversion operation succeeds but the value overflows. |

An OverflowException exception, |

In addition, Single.NaN, Single.PositiveInfinity, and Single.NegativeInfinity throw an OverflowException for conversions to integers in a checked context, but these values overflow when converted to integers in an unchecked context. For conversions to Decimal, they always throw an OverflowException. For conversions to Double, they convert to Double.NaN, Double.PositiveInfinity, and Double.NegativeInfinity, respectively.

Note that a loss of precision may result from converting a Single value to another numeric type. In the case of converting non-integral Double values, as the output from the example shows, the fractional component is lost when the Single value is either rounded (as in Visual Basic) or truncated (as in C#). For conversions to Decimal and Single values, the Double value may not have a precise representation in the target data type.

The following example converts a number of Single values to several other numeric types. The conversions occur in a checked context in Visual Basic (the default) and in C# (because of the checked keyword). The output from the example shows the result for conversions in both a checked an unchecked context. You can perform conversions in an unchecked context in Visual Basic by compiling with the /removeintchecks+ compiler switch and in C# by commenting out the checked statement.

For more information on the conversion of numeric types, see Type Conversion in the .NET Framework and Type Conversion Tables in the .NET Framework.

### Floating-point functionality

The Single structure and related types provide methods to perform the following categories of operations:

Comparison of values. You can call the Equals method to determine whether two Single values are equal, or the CompareTo method to determine the relationship between two values.

The Single 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 Single value is converted to a Double before performing the comparison. If one of the operands is an integral type, it is converted to a Single before performing the comparison. Although these are widening conversions, they may involve a loss of precision.

**Caution**Because of differences in precision, two Single values that you expect to be equal may turn out to be unequal, which affects the result of the comparison. See the Testing for equality section for more information about comparing two Single values.

You can also call the IsNaN, IsInfinity, IsPositiveInfinity, and IsNegativeInfinity 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 Single methods. If the other operand in a mathematical operation is a Double, the Single 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 Single before performing the operation, and the result of the operation is also a Single value.

You can perform other mathematical operations by calling static (Shared in Visual Basic) methods in the System.Math class. These include additional methods commonly used for arithmetic (such as Math.Abs, Math.Sign, and Math.Sqrt), geometry (such as Math.Cos and Math.Sin), and calculus (such as Math.Log). In all cases, the Single value is converted to a Double.

You can also manipulate the individual bits in a Single value. The BitConverter.GetBytes(Single) method returns its bit pattern in a byte array. By passing that byte array to the BitConverter.ToInt32 method, you can also preserve the Single 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 Single value by calling the Math.Round method. However, note that the Single 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 Single value to its string representation by calling the 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 Single value by calling the Parse or TryParse method. If the parse operation fails, the Parse method throws an exception, whereas the TryParse method returns false.

Type conversion. The Single 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 Single values. Conversion of a value of any standard numeric type other than a Double to a Single 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:

Type

Maximum precision (in decimal digits)

Internal precision (in decimal digits)

15

17

10

10

19

19

Single

7

9

The problem of precision most frequently affects Single 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.

#### .NET Framework

Supported in: 4.6, 4.5, 4, 3.5, 3.0, 2.0, 1.1#### .NET Framework Client Profile

Supported in: 4, 3.5 SP1#### XNA Framework

Supported in: 3.0, 2.0, 1.0#### Portable Class Library

Supported in: Portable Class LibrarySupported in: Windows Phone 8.1

Supported in: Windows Phone Silverlight 8.1

Supported in: Windows Phone Silverlight 8

All members of this type are thread safe. Members that appear to modify instance state actually return a new instance initialized with the new value. As with any other type, reading and writing to a shared variable that contains an instance of this type must be protected by a lock to guarantee thread safety.