# Single Struct

## Definition

``public value class Single : IComparable, IComparable<float>, IConvertible, IEquatable<float>, IFormattable``
``public value class Single : IComparable, IConvertible, IFormattable``
``public value class Single : IComparable, IComparable<float>, IEquatable<float>, IFormattable``
``public struct Single : IComparable, IComparable<float>, IConvertible, IEquatable<float>, IFormattable``
``````[System.Serializable]
public struct Single : IComparable, IConvertible, IFormattable``````
``````[System.Runtime.InteropServices.ComVisible(true)]
[System.Serializable]
public struct Single : IComparable, IComparable<float>, IConvertible, IEquatable<float>, IFormattable``````
``public struct Single : IComparable, IComparable<float>, IEquatable<float>, IFormattable``
``````type single = struct
interface IConvertible
interface IFormattable``````
``````type single = struct
interface IFormattable
interface IConvertible``````
``````type single = struct
interface IFormattable``````
``````Public Structure Single
Implements IComparable, IComparable(Of Single), IConvertible, IEquatable(Of Single), IFormattable``````
``````Public Structure Single
Implements IComparable, IConvertible, IFormattable``````
``````Public Structure Single
Implements IComparable, IComparable(Of Single), IEquatable(Of Single), IFormattable``````
Inheritance
Single
Attributes
Implements

## Remarks

Single 值类型表示单精度32位数字，其值范围从负 3.402823 e 38 到正 3.402823 e 38，以及正或负零、PositiveInfinityNegativeInfinity，而不是数字（NaN）。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). 它用于表示非常大的值（例如行星或 galaxies 之间的距离）或极小的值（例如物质的分子质量，以千克为间隔），并且通常不精确（如从地球到另一颗太阳系的距离）。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). Single 类型符合二元浮点算术的 IEC 60559:1989 （IEEE 754）标准。The Single type complies with the IEC 60559:1989 (IEEE 754) standard for binary floating-point arithmetic.

System.Single 提供了一些方法，用于比较此类型的实例，将实例的值转换为其字符串表示形式，并将数字的字符串表示形式转换为此类型的实例。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, Standard Numeric Format Strings, and Custom Numeric Format Strings.

### 浮点表示形式和精度Floating-point representation and precision

Single 数据类型以32位二进制格式存储单精度浮点值，如下表所示：The Single data type stores single-precision floating-point values in a 32-bit binary format, as shown in the following table:

ExponentExponent 23-3023-30
Sign （0 = 正，1 = 负值）Sign (0 = positive, 1 = negative) 3131

``````using System;

public class Example
{
public static void Main()
{
Single value = .2f;
Single result1 = value * 10f;
Single result2 = 0f;
for (int ctr = 1; ctr <= 10; ctr++)
result2 += value;

Console.WriteLine(".2 * 10:           {0:R}", result1);
Console.WriteLine(".2 Added 10 times: {0:R}", result2);
}
}
// The example displays the following output:
//       .2 * 10:           2
//       .2 Added 10 times: 2.00000024
``````
``````Module Example
Public Sub Main()
Dim value As Single = .2
Dim result1 As Single = value * 10
Dim result2 As Single
For ctr As Integer = 1 To 10
result2 += value
Next
Console.WriteLine(".2 * 10:           {0:R}", result1)
Console.WriteLine(".2 Added 10 times: {0:R}", result2)
End Sub
End Module
' The example displays the following output:
'       .2 * 10:           2
'       .2 Added 10 times: 2.00000024
``````

``````using System;

public class Example
{
public static void Main()
{
Single value = 123.456f;
Single additional = Single.Epsilon * 1e15f;
Console.WriteLine(\$"{value} + {additional} = {value + additional}");
}
}
// The example displays the following output:
//    123.456 + 1.401298E-30 = 123.456
``````
``````Module Example
Public Sub Main()
Dim value As Single = 123.456
Dim additional As Single = Single.Epsilon * 1e15
Console.WriteLine(\$"{value} + {additional} = {value + additional}")
End Sub
End Module
' The example displays the following output:
'   123.456 + 1.401298E-30 = 123.456
``````

• 对于特定精度，看起来相等的两个浮点数在进行比较时可能不相等，因为其最小有效位不同。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. 尽管两个值看起来是相同的，但对 `Equals` 方法的调用表示它们不是。Although the two values appear to be the same, a call to the `Equals` method indicates that they are not.

``````using System;

public class Example
{
public static void Main()
{
Single[] values = { 10.01f, 2.88f, 2.88f, 2.88f, 9.0f };
Single result = 27.65f;
Single total = 0f;
foreach (var value in values)
total += value;

if (total.Equals(result))
Console.WriteLine("The sum of the values equals the total.");
else
Console.WriteLine("The sum of the values ({0}) does not equal the total ({1}).",
total, result);
}
}
// The example displays the following output:
//      The sum of the values (27.65) does not equal the total (27.65).
//
// If the index items in the Console.WriteLine statement are changed to {0:R},
// the example displays the following output:
//       The sum of the values (27.6500015) does not equal the total (27.65).
``````
``````Module Example
Public Sub Main()
Dim values() As Single = { 10.01, 2.88, 2.88, 2.88, 9.0 }
Dim result As Single = 27.65
Dim total As Single
For Each value In values
total += value
Next
If total.Equals(result) Then
Console.WriteLine("The sum of the values equals the total.")
Else
Console.WriteLine("The sum of the values ({0}) does not equal the total ({1}).",
total, result)
End If
End Sub
End Module
' The example displays the following output:
'      The sum of the values (27.65) does not equal the total (27.65).
'
' If the index items in the Console.WriteLine statement are changed to {0:R},
' the example displays the following output:
'       The sum of the values (27.639999999999997) does not equal the total (27.64).
``````

如果将 Console.WriteLine(String, Object, Object) 语句中的格式项从 `{0}``{1}` 更改为 `{0:R}`，并使用 `{1:R}` 显示两个 Single 值的所有有效位，则可以清楚地表明这两个值不相等，因为在加法运算期间丢失了精度。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. 在这种情况下，可以通过调用 Math.Round(Double, Int32) 方法，在执行比较之前将 Single 值舍入到所需精度来解决该问题。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. 前面的示例通过显示乘以 .3 乘以10的结果并将 .3 添加到 3 9 次，阐释了这一点。A previous example illustrated this by displaying the result of multiplying .3 by 10 and adding .3 to .3 nine times.

当包含小数值的数值操作的准确性非常重要时，请使用 Decimal 类型，而不要使用 Single 类型。When accuracy in numeric operations with fractional values is important, use the Decimal type instead of the Single type. 当整数值超出 Int64 范围或 UInt64 类型的数值运算的精度很重要时，请使用 BigInteger 类型。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 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. 在下面的示例中，三个 Single 值将转换为字符串，并保存在一个文件中。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.

``````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(values[ctr].ToString());
if (ctr != values.Length - 1)
sw.Write("|");
}
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
``````
``````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
``````

在这种情况下，可以使用 "G9"标准数字格式字符串将值成功舍入，以保留 Single 值的完全精度，如下面的示例所示。In this case, the values can be successfully round-tripped by using the "G9" standard numeric format string to preserve the full precision of Single values, as the following example shows.

``````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:G9}{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
``````
``````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("{0:G9}{1}", values(ctr),
If(ctr < values.Length - 1, "|", ""))
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
``````
• Single 值的精度低于 Double 值。Single values have less precision than Double values. 转换为看似等效的 DoubleSingle 值通常不等于 Double 值，因为精度存在差异。A Single value that is converted to a seemingly equivalent Double often does not equal the Double value because of differences in precision. 在下面的示例中，将相同除法运算的结果分配给 Double 值和 Single 值。In the following example, the result of identical division operations is assigned to a Double value and a Single value. Single 值强制转换为 Double后，这两个值的比较表明它们不相等。After the Single value is cast to a Double, a comparison of the two values shows that they are unequal.

``````using System;

public class Example
{
public static void Main()
{
Double value1 = 1/3.0;
Single sValue2 = 1/3.0f;
Double value2 = (Double) sValue2;
Console.WriteLine("{0:R} = {1:R}: {2}", value1, value2,
value1.Equals(value2));
}
}
// The example displays the following output:
//        0.33333333333333331 = 0.3333333432674408: False
``````
``````Module Example
Public Sub Main()
Dim value1 As Double = 1/3
Dim sValue2 As Single = 1/3
Dim value2 As Double = CDbl(sValue2)
Console.WriteLine("{0} = {1}: {2}", value1, value2, value1.Equals(value2))
End Sub
End Module
' The example displays the following output:
'       0.33333333333333331 = 0.3333333432674408: False
``````

若要避免此问题，请使用 Double 数据类型来代替 Single 数据类型，或使用 Round 方法，使这两个值具有相同的精度。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

``````using System;

public class Example
{
public static void Main()
{
float value1 = .3333333f;
float value2 = 1.0f/3;
Console.WriteLine("{0:R} = {1:R}: {2}", value1, value2, value1.Equals(value2));
}
}
// The example displays the following output:
//        0.3333333 = 0.333333343: False
``````
``````Module Example
Public Sub Main()
Dim value1 As Single = .3333333
Dim value2 As Single = 1/3
Console.WriteLine("{0:R} = {1:R}: {2}", value1, value2, value1.Equals(value2))
End Sub
End Module
' The example displays the following output:
'       0.3333333 = 0.333333343: False
``````

``````using System;

public class Example
{
public static void Main()
{
float value1 = 10.201438f;
value1 = (float) Math.Sqrt((float) Math.Pow(value1, 2));
float value2 = (float) Math.Pow((float) value1 * 3.51f, 2);
value2 = ((float) Math.Sqrt(value2)) / 3.51f;
Console.WriteLine("{0} = {1}: {2}\n",
value1, value2, value1.Equals(value2));
Console.WriteLine("{0:G9} = {1:G9}", value1, value2);
}
}
// The example displays the following output:
//       10.20144 = 10.20144: False
//
//       10.201438 = 10.2014389
``````
``````Module Example
Public Sub Main()
Dim value1 As Single = 10.201438
value1 = CSng(Math.Sqrt(CSng(Math.Pow(value1, 2))))
Dim value2 As Single = CSng(Math.Pow(value1 * CSng(3.51), 2))
value2 = CSng(Math.Sqrt(value2) / CSng(3.51))
Console.WriteLine("{0} = {1}: {2}",
value1, value2, value1.Equals(value2))
Console.WriteLine()
Console.WriteLine("{0:G9} = {1:G9}", value1, value2)
End Sub
End Module
' The example displays the following output:
'       10.20144 = 10.20144: False
'
'       10.201438 = 10.2014389
``````

• 调用 Math.Round 方法，以确保这两个值具有相同的精度。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.

``````using System;

public class Example
{
public static void Main()
{
float value1 = .3333333f;
float value2 = 1.0f/3;
int precision = 7;
value1 = (float) Math.Round(value1, precision);
value2 = (float) Math.Round(value2, precision);
Console.WriteLine("{0:R} = {1:R}: {2}", value1, value2, value1.Equals(value2));
}
}
// The example displays the following output:
//        0.3333333 = 0.3333333: True
``````
``````Module Example
Public Sub Main()
Dim value1 As Single = .3333333
Dim value2 As Single = 1/3
Dim precision As Integer = 7
value1 = CSng(Math.Round(value1, precision))
value2 = CSng(Math.Round(value2, precision))
Console.WriteLine("{0:R} = {1:R}: {2}", value1, value2, value1.Equals(value2))
End Sub
End Module
' The example displays the following output:
'       0.3333333 = 0.3333333: True
``````

请注意，精度问题仍适用于中点值的舍入。Note that the problem of precision still applies to rounding of midpoint values. 有关更多信息，请参见 Math.Round(Double, Int32, MidpointRounding) 方法。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.

Warning

在测试相等性时，Single.Epsilon 有时用作两个 Single 值之间的距离的绝对度量值。Single.Epsilon is sometimes used as an absolute measure of the distance between two Single values when testing for equality. Single.Epsilon 度量值为零的 Single 可以添加到或从中减去的最小可能值。However, Single.Epsilon measures the smallest possible value that can be added to, or subtracted from, a Single whose value is zero. 对于大多数正值和负值 Single 值，Single.Epsilon 的值太小，无法检测到。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.

下面的示例使用后一种方法来定义一个 `IsApproximatelyEqual` 方法，该方法可测试两个值之间的相对差异。The following example uses the latter approach to define an `IsApproximatelyEqual` method that tests the relative difference between two values. 它还将对 `IsApproximatelyEqual` 方法和 Equals(Single) 方法的调用结果进行比较。It also contrasts the result of calls to the `IsApproximatelyEqual` method and the Equals(Single) method.

``````using System;

public class Example
{
public static void Main()
{
float one1 = .1f * 10;
float one2 = 0f;
for (int ctr = 1; ctr <= 10; ctr++)
one2 += .1f;

Console.WriteLine("{0:R} = {1:R}: {2}", one1, one2, one1.Equals(one2));
Console.WriteLine("{0:R} is approximately equal to {1:R}: {2}",
one1, one2,
IsApproximatelyEqual(one1, one2, .000001f));
}

static bool IsApproximatelyEqual(float value1, float value2, float epsilon)
{
// If they are equal anyway, just return True.
if (value1.Equals(value2))
return true;

// Handle NaN, Infinity.
if (Double.IsInfinity(value1) | Double.IsNaN(value1))
return value1.Equals(value2);
else if (Double.IsInfinity(value2) | Double.IsNaN(value2))
return value1.Equals(value2);

// Handle zero to avoid division by zero
double divisor = Math.Max(value1, value2);
if (divisor.Equals(0))
divisor = Math.Min(value1, value2);

return Math.Abs(value1 - value2)/divisor <= epsilon;
}
}
// The example displays the following output:
//       1 = 1.00000012: False
//       1 is approximately equal to 1.00000012: True
``````
``````Module Example
Public Sub Main()
Dim one1 As Single = .1 * 10
Dim one2 As Single = 0
For ctr As Integer = 1 To 10
one2 += CSng(.1)
Next
Console.WriteLine("{0:R} = {1:R}: {2}", one1, one2, one1.Equals(one2))
Console.WriteLine("{0:R} is approximately equal to {1:R}: {2}",
one1, one2,
IsApproximatelyEqual(one1, one2, .000001))
End Sub

Function IsApproximatelyEqual(value1 As Single, value2 As Single,
epsilon As Single) As Boolean
' If they are equal anyway, just return True.
If value1.Equals(value2) Then Return True

' Handle NaN, Infinity.
If Single.IsInfinity(value1) Or Single.IsNaN(value1) Then
Return value1.Equals(value2)
Else If Single.IsInfinity(value2) Or Single.IsNaN(value2)
Return value1.Equals(value2)
End If

' Handle zero to avoid division by zero
Dim divisor As Single = Math.Max(value1, value2)
If divisor.Equals(0) Then
divisor = Math.Min(value1, value2)
End If

Return Math.Abs(value1 - value2)/divisor <= epsilon
End Function
End Module
' The example displays the following output:
'       1 = 1.00000012: False
'       1 is approximately equal to 1.00000012: True
``````

### 浮点值和异常Floating-point values and exceptions

• 如果浮点运算的结果对于目标格式来说太小，则结果为零。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.

``````using System;

public class Example
{
public static void Main()
{
float value1 = 1.163287e-36f;
float value2 = 9.164234e-25f;
float result = value1 * value2;
Console.WriteLine("{0} * {1} = {2}", value1, value2, result);
Console.WriteLine("{0} = 0: {1}", result, result.Equals(0.0f));
}
}
// The example displays the following output:
//       1.163287E-36 * 9.164234E-25 = 0
//       0 = 0: True
``````
``````Module Example
Public Sub Main()
Dim value1 As Single = 1.163287e-36
Dim value2 As Single = 9.164234e-25
Dim result As Single = value1 * value2
Console.WriteLine("{0} * {1} = {2:R}", value1, value2, result)
Console.WriteLine("{0} = 0: {1}", result, result.Equals(0))
End Sub
End Module
' The example displays the following output:
'       1.163287E-36 * 9.164234E-25 = 0
'       0 = 0: True
``````
• 如果浮点运算的结果量超过目标格式的范围，则操作的结果将 PositiveInfinityNegativeInfinity，以适合于结果的符号。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. PositiveInfinitySingle.MaxValue 溢出的操作的结果，并 NegativeInfinity溢出 Single.MinValue 的操作的结果，如下面的示例所示。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.

``````using System;

public class Example
{
public static void Main()
{
float value1 = 3.065e35f;
float value2 = 6.9375e32f;
float result = value1 * value2;
Console.WriteLine("PositiveInfinity: {0}",
Single.IsPositiveInfinity(result));
Console.WriteLine("NegativeInfinity: {0}\n",
Single.IsNegativeInfinity(result));

value1 = -value1;
result = value1 * value2;
Console.WriteLine("PositiveInfinity: {0}",
Single.IsPositiveInfinity(result));
Console.WriteLine("NegativeInfinity: {0}",
Single.IsNegativeInfinity(result));
}
}

// The example displays the following output:
//       PositiveInfinity: True
//       NegativeInfinity: False
//
//       PositiveInfinity: False
//       NegativeInfinity: True
``````
``````Module Example
Public Sub Main()
Dim value1 As Single = 3.065e35
Dim value2 As Single = 6.9375e32
Dim result As Single = value1 * value2
Console.WriteLine("PositiveInfinity: {0}",
Single.IsPositiveInfinity(result))
Console.WriteLine("NegativeInfinity: {0}",
Single.IsNegativeInfinity(result))
Console.WriteLine()
value1 = -value1
result = value1 * value2
Console.WriteLine("PositiveInfinity: {0}",
Single.IsPositiveInfinity(result))
Console.WriteLine("NegativeInfinity: {0}",
Single.IsNegativeInfinity(result))
End Sub
End Module
' The example displays the following output:
'       PositiveInfinity: True
'       NegativeInfinity: False
'
'       PositiveInfinity: False
'       NegativeInfinity: True
``````

PositiveInfinity 还会导致除以零的除法运算，负被除数，并 NegativeInfinity 除以零的结果，并以负被除数。PositiveInfinity also results from a division by zero with a positive dividend, and NegativeInfinity results from a division by zero with a negative dividend.

• 如果浮点操作无效，则会 NaN操作的结果。If a floating-point operation is invalid, the result of the operation is NaN. 例如，NaN 以下操作的结果：For example, NaN results from the following operations:

• 除数为零的除以零。Division by zero with a dividend of zero. 请注意，除数为零的其他情况会导致 PositiveInfinityNegativeInfinityNote that other cases of division by zero result in either PositiveInfinity or NegativeInfinity.

• 具有无效输入的任何浮点运算。Any floating-point operation with invalid input. 例如，尝试查找负值的平方根将返回 NaNFor example, attempting to find the square root of a negative value returns NaN.

• 任何具有参数值为 Single.NaN的操作。Any operation with an argument whose value is Single.NaN.

### 类型转换和单结构Type conversions and the Single structure

Single 结构未定义任何显式或隐式转换运算符;相反，转换是由编译器实现的。The Single structure does not define any explicit or implicit conversion operators; instead, conversions are implemented by the compiler.

Conversion from 扩大/收缩Widening/narrowing 可能丢失精度Possible loss of precision
Byte WideningWidening No
Decimal WideningWidening

Double 收缩超出范围的值将转换为 Double.NegativeInfinityDouble.PositiveInfinityNarrowing; out-of-range values are converted to Double.NegativeInfinity or Double.PositiveInfinity. 可以。Yes. Double 支持17个十进制数字的精度;Single 支持9。Double supports 17 decimal digits of precision; Single supports 9.
Int16 WideningWidening No
Int32 WideningWidening 可以。Yes. Int32 支持10个十进制数字的精度;Single 支持9。Int32 supports 10 decimal digits of precision; Single supports 9.
Int64 WideningWidening 可以。Yes. Int64 支持19个十进制数字的精度;Single 支持9。Int64 supports 19 decimal digits of precision; Single supports 9.
SByte WideningWidening No
UInt16 WideningWidening No
UInt32 WideningWidening 可以。Yes. UInt32 支持10个十进制数字的精度;Single 支持9。UInt32 supports 10 decimal digits of precision; Single supports 9.
UInt64 WideningWidening 可以。Yes. Int64 支持20个十进制数字的精度;Single 支持9。Int64 supports 20 decimal digits of precision; Single supports 9.

``````using System;

public class Example
{
public static void Main()
{
dynamic[] values = { Byte.MinValue, Byte.MaxValue, Decimal.MinValue,
Decimal.MaxValue, Double.MinValue, Double.MaxValue,
Int16.MinValue, Int16.MaxValue, Int32.MinValue,
Int32.MaxValue, Int64.MinValue, Int64.MaxValue,
SByte.MinValue, SByte.MaxValue, UInt16.MinValue,
UInt16.MaxValue, UInt32.MinValue, UInt32.MaxValue,
UInt64.MinValue, UInt64.MaxValue };
float sngValue;
foreach (var value in values) {
if (value.GetType() == typeof(Decimal) ||
value.GetType() == typeof(Double))
sngValue = (float) value;
else
sngValue = value;
Console.WriteLine("{0} ({1}) --> {2:R} ({3})",
value, value.GetType().Name,
sngValue, sngValue.GetType().Name);
}
}
}
// The example displays the following output:
//       0 (Byte) --> 0 (Single)
//       255 (Byte) --> 255 (Single)
//       -79228162514264337593543950335 (Decimal) --> -7.92281625E+28 (Single)
//       79228162514264337593543950335 (Decimal) --> 7.92281625E+28 (Single)
//       -1.79769313486232E+308 (Double) --> -Infinity (Single)
//       1.79769313486232E+308 (Double) --> Infinity (Single)
//       -32768 (Int16) --> -32768 (Single)
//       32767 (Int16) --> 32767 (Single)
//       -2147483648 (Int32) --> -2.14748365E+09 (Single)
//       2147483647 (Int32) --> 2.14748365E+09 (Single)
//       -9223372036854775808 (Int64) --> -9.223372E+18 (Single)
//       9223372036854775807 (Int64) --> 9.223372E+18 (Single)
//       -128 (SByte) --> -128 (Single)
//       127 (SByte) --> 127 (Single)
//       0 (UInt16) --> 0 (Single)
//       65535 (UInt16) --> 65535 (Single)
//       0 (UInt32) --> 0 (Single)
//       4294967295 (UInt32) --> 4.2949673E+09 (Single)
//       0 (UInt64) --> 0 (Single)
//       18446744073709551615 (UInt64) --> 1.84467441E+19 (Single)
``````
``````Module Example
Public Sub Main()
Dim values() As Object = { Byte.MinValue, Byte.MaxValue, Decimal.MinValue,
Decimal.MaxValue, Double.MinValue, Double.MaxValue,
Int16.MinValue, Int16.MaxValue, Int32.MinValue,
Int32.MaxValue, Int64.MinValue, Int64.MaxValue,
SByte.MinValue, SByte.MaxValue, UInt16.MinValue,
UInt16.MaxValue, UInt32.MinValue, UInt32.MaxValue,
UInt64.MinValue, UInt64.MaxValue }
Dim sngValue As Single
For Each value In values
If value.GetType() = GetType(Double) Then
sngValue = CSng(value)
Else
sngValue = value
End If
Console.WriteLine("{0} ({1}) --> {2:R} ({3})",
value, value.GetType().Name,
sngValue, sngValue.GetType().Name)
Next
End Sub
End Module
' The example displays the following output:
'       0 (Byte) --> 0 (Single)
'       255 (Byte) --> 255 (Single)
'       -79228162514264337593543950335 (Decimal) --> -7.92281625E+28 (Single)
'       79228162514264337593543950335 (Decimal) --> 7.92281625E+28 (Single)
'       -1.79769313486232E+308 (Double) --> -Infinity (Single)
'       1.79769313486232E+308 (Double) --> Infinity (Single)
'       -32768 (Int16) --> -32768 (Single)
'       32767 (Int16) --> 32767 (Single)
'       -2147483648 (Int32) --> -2.14748365E+09 (Single)
'       2147483647 (Int32) --> 2.14748365E+09 (Single)
'       -9223372036854775808 (Int64) --> -9.223372E+18 (Single)
'       9223372036854775807 (Int64) --> 9.223372E+18 (Single)
'       -128 (SByte) --> -128 (Single)
'       127 (SByte) --> 127 (Single)
'       0 (UInt16) --> 0 (Single)
'       65535 (UInt16) --> 65535 (Single)
'       0 (UInt32) --> 0 (Single)
'       4294967295 (UInt32) --> 4.2949673E+09 (Single)
'       0 (UInt64) --> 0 (Single)
'       18446744073709551615 (UInt64) --> 1.84467441E+19 (Single)
``````

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

Single 值转换为 Double 是扩大转换。The conversion of a Single value to a Double is a widening conversion. 如果 Double 类型没有 Single 值的精确表示形式，转换可能会导致精度损失。The conversion may result in a loss of precision if the Double type does not have a precise representation for the Single value.

Single 值转换为任何基元数值数据类型（而非 Double）的值是收缩转换，需要转换运算符（在中C#）或转换方法（在 Visual Basic 中）。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). 超出目标数据类型范围的值（由目标类型的 `MinValue``MaxValue` 属性定义）的行为如下表中所示。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.

Decimal An OverflowException exception,

``````using System;

public class Example
{
public static void Main()
{
float[] values = { Single.MinValue, -67890.1234f, -12345.6789f,
12345.6789f, 67890.1234f, Single.MaxValue,
Single.NaN, Single.PositiveInfinity,
Single.NegativeInfinity };
checked {
foreach (var value in values) {
try {
Int64 lValue = (long) value;
Console.WriteLine("{0} ({1}) --> {2} (0x{2:X16}) ({3})",
value, value.GetType().Name,
lValue, lValue.GetType().Name);
}
catch (OverflowException) {
Console.WriteLine("Unable to convert {0} to Int64.", value);
}
try {
UInt64 ulValue = (ulong) value;
Console.WriteLine("{0} ({1}) --> {2} (0x{2:X16}) ({3})",
value, value.GetType().Name,
ulValue, ulValue.GetType().Name);
}
catch (OverflowException) {
Console.WriteLine("Unable to convert {0} to UInt64.", value);
}
try {
Decimal dValue = (decimal) value;
Console.WriteLine("{0} ({1}) --> {2} ({3})",
value, value.GetType().Name,
dValue, dValue.GetType().Name);
}
catch (OverflowException) {
Console.WriteLine("Unable to convert {0} to Decimal.", value);
}

Double dblValue = value;
Console.WriteLine("{0} ({1}) --> {2} ({3})",
value, value.GetType().Name,
dblValue, dblValue.GetType().Name);
Console.WriteLine();
}
}
}
}
// The example displays the following output for conversions performed
// in a checked context:
//       Unable to convert -3.402823E+38 to Int64.
//       Unable to convert -3.402823E+38 to UInt64.
//       Unable to convert -3.402823E+38 to Decimal.
//       -3.402823E+38 (Single) --> -3.40282346638529E+38 (Double)
//
//       -67890.13 (Single) --> -67890 (0xFFFFFFFFFFFEF6CE) (Int64)
//       Unable to convert -67890.13 to UInt64.
//       -67890.13 (Single) --> -67890.12 (Decimal)
//       -67890.13 (Single) --> -67890.125 (Double)
//
//       -12345.68 (Single) --> -12345 (0xFFFFFFFFFFFFCFC7) (Int64)
//       Unable to convert -12345.68 to UInt64.
//       -12345.68 (Single) --> -12345.68 (Decimal)
//       -12345.68 (Single) --> -12345.6787109375 (Double)
//
//       12345.68 (Single) --> 12345 (0x0000000000003039) (Int64)
//       12345.68 (Single) --> 12345 (0x0000000000003039) (UInt64)
//       12345.68 (Single) --> 12345.68 (Decimal)
//       12345.68 (Single) --> 12345.6787109375 (Double)
//
//       67890.13 (Single) --> 67890 (0x0000000000010932) (Int64)
//       67890.13 (Single) --> 67890 (0x0000000000010932) (UInt64)
//       67890.13 (Single) --> 67890.12 (Decimal)
//       67890.13 (Single) --> 67890.125 (Double)
//
//       Unable to convert 3.402823E+38 to Int64.
//       Unable to convert 3.402823E+38 to UInt64.
//       Unable to convert 3.402823E+38 to Decimal.
//       3.402823E+38 (Single) --> 3.40282346638529E+38 (Double)
//
//       Unable to convert NaN to Int64.
//       Unable to convert NaN to UInt64.
//       Unable to convert NaN to Decimal.
//       NaN (Single) --> NaN (Double)
//
//       Unable to convert Infinity to Int64.
//       Unable to convert Infinity to UInt64.
//       Unable to convert Infinity to Decimal.
//       Infinity (Single) --> Infinity (Double)
//
//       Unable to convert -Infinity to Int64.
//       Unable to convert -Infinity to UInt64.
//       Unable to convert -Infinity to Decimal.
//       -Infinity (Single) --> -Infinity (Double)
// The example displays the following output for conversions performed
// in an unchecked context:
//       -3.402823E+38 (Single) --> -9223372036854775808 (0x8000000000000000) (Int64)
//       -3.402823E+38 (Single) --> 9223372036854775808 (0x8000000000000000) (UInt64)
//       Unable to convert -3.402823E+38 to Decimal.
//       -3.402823E+38 (Single) --> -3.40282346638529E+38 (Double)
//
//       -67890.13 (Single) --> -67890 (0xFFFFFFFFFFFEF6CE) (Int64)
//       -67890.13 (Single) --> 18446744073709483726 (0xFFFFFFFFFFFEF6CE) (UInt64)
//       -67890.13 (Single) --> -67890.12 (Decimal)
//       -67890.13 (Single) --> -67890.125 (Double)
//
//       -12345.68 (Single) --> -12345 (0xFFFFFFFFFFFFCFC7) (Int64)
//       -12345.68 (Single) --> 18446744073709539271 (0xFFFFFFFFFFFFCFC7) (UInt64)
//       -12345.68 (Single) --> -12345.68 (Decimal)
//       -12345.68 (Single) --> -12345.6787109375 (Double)
//
//       12345.68 (Single) --> 12345 (0x0000000000003039) (Int64)
//       12345.68 (Single) --> 12345 (0x0000000000003039) (UInt64)
//       12345.68 (Single) --> 12345.68 (Decimal)
//       12345.68 (Single) --> 12345.6787109375 (Double)
//
//       67890.13 (Single) --> 67890 (0x0000000000010932) (Int64)
//       67890.13 (Single) --> 67890 (0x0000000000010932) (UInt64)
//       67890.13 (Single) --> 67890.12 (Decimal)
//       67890.13 (Single) --> 67890.125 (Double)
//
//       3.402823E+38 (Single) --> -9223372036854775808 (0x8000000000000000) (Int64)
//       3.402823E+38 (Single) --> 0 (0x0000000000000000) (UInt64)
//       Unable to convert 3.402823E+38 to Decimal.
//       3.402823E+38 (Single) --> 3.40282346638529E+38 (Double)
//
//       NaN (Single) --> -9223372036854775808 (0x8000000000000000) (Int64)
//       NaN (Single) --> 0 (0x0000000000000000) (UInt64)
//       Unable to convert NaN to Decimal.
//       NaN (Single) --> NaN (Double)
//
//       Infinity (Single) --> -9223372036854775808 (0x8000000000000000) (Int64)
//       Infinity (Single) --> 0 (0x0000000000000000) (UInt64)
//       Unable to convert Infinity to Decimal.
//       Infinity (Single) --> Infinity (Double)
//
//       -Infinity (Single) --> -9223372036854775808 (0x8000000000000000) (Int64)
//       -Infinity (Single) --> 9223372036854775808 (0x8000000000000000) (UInt64)
//       Unable to convert -Infinity to Decimal.
//       -Infinity (Single) --> -Infinity (Double)
``````
``````Module Example
Public Sub Main()
Dim values() As Single = { Single.MinValue, -67890.1234, -12345.6789,
12345.6789, 67890.1234, Single.MaxValue,
Single.NaN, Single.PositiveInfinity,
Single.NegativeInfinity }
For Each value In values
Try
Dim lValue As Long = CLng(value)
Console.WriteLine("{0} ({1}) --> {2} (0x{2:X16}) ({3})",
value, value.GetType().Name,
lValue, lValue.GetType().Name)
Catch e As OverflowException
Console.WriteLine("Unable to convert {0} to Int64.", value)
End Try
Try
Dim ulValue As UInt64 = CULng(value)
Console.WriteLine("{0} ({1}) --> {2} (0x{2:X16}) ({3})",
value, value.GetType().Name,
ulValue, ulValue.GetType().Name)
Catch e As OverflowException
Console.WriteLine("Unable to convert {0} to UInt64.", value)
End Try
Try
Dim dValue As Decimal = CDec(value)
Console.WriteLine("{0} ({1}) --> {2} ({3})",
value, value.GetType().Name,
dValue, dValue.GetType().Name)
Catch e As OverflowException
Console.WriteLine("Unable to convert {0} to Decimal.", value)
End Try

Dim dblValue As Double = value
Console.WriteLine("{0} ({1}) --> {2} ({3})",
value, value.GetType().Name,
dblValue, dblValue.GetType().Name)
Console.WriteLine()
Next
End Sub
End Module
' The example displays the following output for conversions performed
' in a checked context:
'       Unable to convert -3.402823E+38 to Int64.
'       Unable to convert -3.402823E+38 to UInt64.
'       Unable to convert -3.402823E+38 to Decimal.
'       -3.402823E+38 (Single) --> -3.40282346638529E+38 (Double)
'
'       -67890.13 (Single) --> -67890 (0xFFFFFFFFFFFEF6CE) (Int64)
'       Unable to convert -67890.13 to UInt64.
'       -67890.13 (Single) --> -67890.12 (Decimal)
'       -67890.13 (Single) --> -67890.125 (Double)
'
'       -12345.68 (Single) --> -12346 (0xFFFFFFFFFFFFCFC6) (Int64)
'       Unable to convert -12345.68 to UInt64.
'       -12345.68 (Single) --> -12345.68 (Decimal)
'       -12345.68 (Single) --> -12345.6787109375 (Double)
'
'       12345.68 (Single) --> 12346 (0x000000000000303A) (Int64)
'       12345.68 (Single) --> 12346 (0x000000000000303A) (UInt64)
'       12345.68 (Single) --> 12345.68 (Decimal)
'       12345.68 (Single) --> 12345.6787109375 (Double)
'
'       67890.13 (Single) --> 67890 (0x0000000000010932) (Int64)
'       67890.13 (Single) --> 67890 (0x0000000000010932) (UInt64)
'       67890.13 (Single) --> 67890.12 (Decimal)
'       67890.13 (Single) --> 67890.125 (Double)
'
'       Unable to convert 3.402823E+38 to Int64.
'       Unable to convert 3.402823E+38 to UInt64.
'       Unable to convert 3.402823E+38 to Decimal.
'       3.402823E+38 (Single) --> 3.40282346638529E+38 (Double)
'
'       Unable to convert NaN to Int64.
'       Unable to convert NaN to UInt64.
'       Unable to convert NaN to Decimal.
'       NaN (Single) --> NaN (Double)
'
'       Unable to convert Infinity to Int64.
'       Unable to convert Infinity to UInt64.
'       Unable to convert Infinity to Decimal.
'       Infinity (Single) --> Infinity (Double)
'
'       Unable to convert -Infinity to Int64.
'       Unable to convert -Infinity to UInt64.
'       Unable to convert -Infinity to Decimal.
'       -Infinity (Single) --> -Infinity (Double)
' The example displays the following output for conversions performed
' in an unchecked context:
'       -3.402823E+38 (Single) --> -9223372036854775808 (0x8000000000000000) (Int64)
'       -3.402823E+38 (Single) --> 9223372036854775808 (0x8000000000000000) (UInt64)
'       Unable to convert -3.402823E+38 to Decimal.
'       -3.402823E+38 (Single) --> -3.40282346638529E+38 (Double)
'
'       -67890.13 (Single) --> -67890 (0xFFFFFFFFFFFEF6CE) (Int64)
'       -67890.13 (Single) --> 18446744073709483726 (0xFFFFFFFFFFFEF6CE) (UInt64)
'       -67890.13 (Single) --> -67890.12 (Decimal)
'       -67890.13 (Single) --> -67890.125 (Double)
'
'       -12345.68 (Single) --> -12346 (0xFFFFFFFFFFFFCFC6) (Int64)
'       -12345.68 (Single) --> 18446744073709539270 (0xFFFFFFFFFFFFCFC6) (UInt64)
'       -12345.68 (Single) --> -12345.68 (Decimal)
'       -12345.68 (Single) --> -12345.6787109375 (Double)
'
'       12345.68 (Single) --> 12346 (0x000000000000303A) (Int64)
'       12345.68 (Single) --> 12346 (0x000000000000303A) (UInt64)
'       12345.68 (Single) --> 12345.68 (Decimal)
'       12345.68 (Single) --> 12345.6787109375 (Double)
'
'       67890.13 (Single) --> 67890 (0x0000000000010932) (Int64)
'       67890.13 (Single) --> 67890 (0x0000000000010932) (UInt64)
'       67890.13 (Single) --> 67890.12 (Decimal)
'       67890.13 (Single) --> 67890.125 (Double)
'
'       3.402823E+38 (Single) --> -9223372036854775808 (0x8000000000000000) (Int64)
'       3.402823E+38 (Single) --> 0 (0x0000000000000000) (UInt64)
'       Unable to convert 3.402823E+38 to Decimal.
'       3.402823E+38 (Single) --> 3.40282346638529E+38 (Double)
'
'       NaN (Single) --> -9223372036854775808 (0x8000000000000000) (Int64)
'       NaN (Single) --> 0 (0x0000000000000000) (UInt64)
'       Unable to convert NaN to Decimal.
'       NaN (Single) --> NaN (Double)
'
'       Infinity (Single) --> -9223372036854775808 (0x8000000000000000) (Int64)
'       Infinity (Single) --> 0 (0x0000000000000000) (UInt64)
'       Unable to convert Infinity to Decimal.
'       Infinity (Single) --> Infinity (Double)
'
'       -Infinity (Single) --> -9223372036854775808 (0x8000000000000000) (Int64)
'       -Infinity (Single) --> 9223372036854775808 (0x8000000000000000) (UInt64)
'       Unable to convert -Infinity to Decimal.
'       -Infinity (Single) --> -Infinity (Double)
``````

### 浮点型功能Floating-point functionality

Single 结构和相关类型提供了执行以下类别的操作的方法：The Single structure and related types provide methods to perform the following categories of operations:

• 值比较Comparison of values. 您可以调用 Equals 方法来确定两个 Single 值是否相等，或 CompareTo 方法来确定两个值之间的关系。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.

Single 结构还支持一组完整的比较运算符。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. 如果其中一个操作数是 Double，则在执行比较之前 Single 值将转换为 DoubleIf one of the operands is a Double, the Single value is converted to a Double before performing the comparison. 如果其中一个操作数为整型类型，则在执行比较之前将其转换为 SingleIf 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.

Warning

由于精度存在差异，因此两个预期相等 Single 值可能会不相等，这将影响比较的结果。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. 请参阅测试相等性部分，了解有关比较两个 Single 值的详细信息。See the Testing for equality section for more information about comparing two Single values.

还可以调用 IsNaNIsInfinityIsPositiveInfinityIsNegativeInfinity 方法来测试这些特殊值。You can also call the IsNaN, IsInfinity, IsPositiveInfinity, and IsNegativeInfinity methods to test for these special values.

• 数学运算Mathematical operations. 常见算术运算（例如加法、减法、乘法和除法）由语言编译器和公共中间语言（CIL）指令实现，而不是通过 Single 方法实现。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. 如果数学运算中的另一个操作数是 Double，则 Single 在执行运算前转换为 Double，并且操作的结果也是 Double 值。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. 如果另一个操作数是整数类型，则在执行操作之前会将其转换为 Single，并且操作的结果也是 Single 值。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.

您可以通过在 System.Math 类中调用 `static``Shared` Visual Basic）方法来执行其他数学运算。You can perform other mathematical operations by calling `static` (`Shared` in Visual Basic) methods in the System.Math class. 其中包括通常用于算法的其他方法（例如 Math.AbsMath.SignMath.Sqrt）、几何（如 Math.CosMath.Sin）以及微积分（如 Math.Log）。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). 在所有情况下，Single 值都将转换为 DoubleIn all cases, the Single value is converted to a Double.

您还可以操作 Single 值中的单个位。You can also manipulate the individual bits in a Single value. BitConverter.GetBytes(Single) 方法将其位模式返回到字节数组中。The BitConverter.GetBytes(Single) method returns its bit pattern in a byte array. 通过将该字节数组传递到 BitConverter.ToInt32 方法，还可以保留32位整数中的 Single 值的位模式。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. 可以通过调用 Math.Round 方法来舍入 Single 值。You can round a Single value by calling the Math.Round method. 但请注意，在调用方法之前，Single 值将转换为 Double，转换可能会导致精度损失。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. 可以通过调用 ToString 方法或通过使用复合格式设置功能，将 Single 值转换为其字符串表示形式。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. 可以通过调用 ParseTryParse 方法，将浮点值的字符串表示形式转换为 Single 值。You can convert the string representation of a floating-point value to a Single value by calling the Parse or TryParse method. 如果分析操作失败，Parse 方法将引发异常，而 TryParse 方法返回 `false`If the parse operation fails, the Parse method throws an exception, whereas the TryParse method returns `false`.

• 类型转换Type conversion. Single 结构提供 IConvertible 接口的显式接口实现，该接口支持任意两种标准 .NET Framework 数据类型之间的转换。The Single structure provides an explicit interface implementation for the IConvertible interface, which supports conversion between any two standard .NET Framework data types. 语言编译器还支持所有其他标准数值类型的值的隐式转换，但 Double 转换为 Single 值。Language compilers also support the implicit conversion of values for all other standard numeric types except for the conversion of Double to Single values. Double 以外的任何标准数值类型的值转换为 Single 是扩大转换，不需要使用强制转换运算符或转换方法。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.

但是，32位和64位整数值的转换可能会导致精度损失。However, conversion of 32-bit and 64-bit integer values can involve a loss of precision. 下表列出了32位、64位和 Double 类型的精度差异：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)
Double 1515 1717
Int32 and UInt32 1010 1010
Int64 and UInt64 1919 1919
Single 77 99

精确的问题会影响转换为 DoubleSingle 值。The problem of precision most frequently affects Single values that are converted to Double values. 在下面的示例中，两个由相同除法运算生成的值是不相等的，因为其中一个值是转换为 Double的单精度浮点值。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.

``````using System;

public class Example
{
public static void Main()
{
Double value1 = 1/3.0;
Single sValue2 = 1/3.0f;
Double value2 = (Double) sValue2;
Console.WriteLine("{0:R} = {1:R}: {2}", value1, value2,
value1.Equals(value2));
}
}
// The example displays the following output:
//        0.33333333333333331 = 0.3333333432674408: False
``````
``````Module Example
Public Sub Main()
Dim value1 As Double = 1/3
Dim sValue2 As Single = 1/3
Dim value2 As Double = CDbl(sValue2)
Console.WriteLine("{0} = {1}: {2}", value1, value2, value1.Equals(value2))
End Sub
End Module
' The example displays the following output:
'       0.33333333333333331 = 0.3333333432674408: False
``````

## Fields

 表示大于零的最小正 Single 值。Represents the smallest positive Single value that is greater than zero. 此字段是常量。This field is constant. 表示 Single 的最大可能值。Represents the largest possible value of Single. 此字段是常量。This field is constant. 表示 Single 的最小可能值。Represents the smallest possible value of Single. 此字段是常量。This field is constant. 表示非数字 (`NaN`)。Represents not a number (`NaN`). 此字段是常量。This field is constant. 表示负无穷。Represents negative infinity. 此字段是常量。This field is constant. 表示正无穷。Represents positive infinity. 此字段是常量。This field is constant.

## Methods

 将此实例与指定对象进行比较，并返回一个整数，该整数指示此实例的值是小于、等于还是大于指定对象的值。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. 将此实例与指定的单精度浮点数进行比较，并返回一个整数，该整数指示此实例的值是小于、等于还是大于指定单精度浮点数的值。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. 返回一个值，该值指示此实例是否等于指定对象。Returns a value indicating whether this instance is equal to a specified object. 返回一个值，该值指示此实例和指定的 Single 对象是否表示相同的值。Returns a value indicating whether this instance and a specified Single object represent the same value. 返回此实例的哈希代码。Returns the hash code for this instance. 返回值类型 TypeCode 的 Single。Returns the TypeCode for value type Single. 确定指定值是否为有限（零、次正规数或正规数）。Determines whether the specified value is finite (zero, subnormal or normal). 返回一个值，该值指示指定数字是计算为负无穷大还是正无穷大。Returns a value indicating whether the specified number evaluates to negative or positive infinity. 返回一个值，该值指示指定的值是否不为数字 (NaN)。Returns a value that indicates whether the specified value is not a number (NaN). 确定指定值是否为负值。Determines whether the specified value is negative. 返回一个值，通过该值指示指定数字是否计算为负无穷大。Returns a value indicating whether the specified number evaluates to negative infinity. 确定指定值是否为正规数。Determines whether the specified value is normal. 返回一个值，通过该值指示指定数字是否计算为正无穷大。Returns a value indicating whether the specified number evaluates to positive infinity. 确定指定值是否是次正规数。Determines whether the specified value is subnormal. 将字符范围（其中包含指定样式和区域性特定格式的数字的字符串表示形式）转换为它的等效单精度浮点数。Converts a character span that contains the string representation of a number in a specified style and culture-specific format to its single-precision floating-point number equivalent. 将数字的字符串表示形式转换为它的等效单精度浮点数。Converts the string representation of a number to its single-precision floating-point number equivalent. 将具有指定区域性特定格式的数字的字符串表示形式转换为它的等效单精度浮点数。Converts the string representation of a number in a specified culture-specific format to its single-precision floating-point number equivalent. 将具有指定样式的数字的字符串表示形式转换为它的等效单精度浮点数。Converts the string representation of a number in a specified style to its single-precision floating-point number equivalent. 将具有指定样式和区域性特定格式的数字的字符串表示形式转换为它的等效单精度浮点数。Converts the string representation of a number in a specified style and culture-specific format to its single-precision floating-point number equivalent. 将此实例的数值转换为其等效的字符串表示形式。Converts the numeric value of this instance to its equivalent string representation. 使用指定的区域性特定格式信息，将此实例的数值转换为它的等效字符串表示形式。Converts the numeric value of this instance to its equivalent string representation using the specified culture-specific format information. 使用指定的格式，将此实例的数值转换为它的等效字符串表示形式。Converts the numeric value of this instance to its equivalent string representation, using the specified format. 使用指定的格式和区域性特定格式信息，将此实例的数值转换为它的等效字符串表示形式。Converts the numeric value of this instance to its equivalent string representation using the specified format and culture-specific format information. 尝试将当前浮点数实例的值的格式设置为提供的字符范围。Tries to format the value of the current float number instance into the provided span of characters. 将具有指定样式和区域性特定格式的数字的范围表示形式转换为它的等效单精度浮点数。Converts the span 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. 将字符范围中的数字的字符串表示形式转换为它的等效单精度浮点数。Converts the string representation of a number in a character span to its single-precision floating-point number equivalent. 一个指示转换是否成功的返回值。A return value indicates whether the conversion succeeded or failed. 将具有指定样式和区域性特定格式的数字的字符串表示形式转换为它的等效单精度浮点数。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. 将数字的字符串表示形式转换为它的等效单精度浮点数。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.

## Operators

 返回一个值，该值指示两个指定的 Single 值是否相等。Returns a value that indicates whether two specified Single values are equal. 返回一个值，该值指示指定的 Single 值是否大于另一个指定的 Single 值。Returns a value that indicates whether a specified Single value is greater than another specified Single value. 返回一个值，该值指示指定的 Single 值是否大于或等于另一个指定的 Single 值。Returns a value that indicates whether a specified Single value is greater than or equal to another specified Single value. 返回一个值，该值指示两个指定的 Single 值是否不相等。Returns a value that indicates whether two specified Single values are not equal. 返回一个值，该值指示指定的 Single 值是否小于另一个指定的 Single 值。Returns a value that indicates whether a specified Single value is less than another specified Single value. 返回一个值，该值指示指定的 Single 值是否小于或等于另一个指定的 Single 值。Returns a value that indicates whether a specified Single value is less than or equal to another specified Single value.

## Explicit Interface Implementations

 将当前实例与同一类型的另一个对象进行比较，并返回一个整数，该整数指示当前实例在排序顺序中的位置是位于另一个对象之前、之后还是与其位置相同。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. 返回此实例的 TypeCode。Returns the TypeCode for this instance. 有关此成员的说明，请参见 ToBoolean(IFormatProvider)。For a description of this member, see ToBoolean(IFormatProvider). 有关此成员的说明，请参见 ToByte(IFormatProvider)。For a description of this member, see ToByte(IFormatProvider). 不支持此转换。This conversion is not supported. 尝试使用此方法将引发 InvalidCastException。Attempting to use this method throws an InvalidCastException. 不支持此转换。This conversion is not supported. 尝试使用此方法将引发 InvalidCastException。Attempting to use this method throws an InvalidCastException. 有关此成员的说明，请参见 ToDecimal(IFormatProvider)。For a description of this member, see ToDecimal(IFormatProvider). 有关此成员的说明，请参见 ToDouble(IFormatProvider)。For a description of this member, see ToDouble(IFormatProvider). 有关此成员的说明，请参见 ToInt16(IFormatProvider)。For a description of this member, see ToInt16(IFormatProvider). 有关此成员的说明，请参见 ToInt32(IFormatProvider)。For a description of this member, see ToInt32(IFormatProvider). 有关此成员的说明，请参见 ToInt64(IFormatProvider)。For a description of this member, see ToInt64(IFormatProvider). 有关此成员的说明，请参见 ToSByte(IFormatProvider)。For a description of this member, see ToSByte(IFormatProvider). 有关此成员的说明，请参见 ToSingle(IFormatProvider)。For a description of this member, see ToSingle(IFormatProvider). 有关此成员的说明，请参见 ToType(Type, IFormatProvider)。For a description of this member, see ToType(Type, IFormatProvider). 有关此成员的说明，请参见 ToUInt16(IFormatProvider)。For a description of this member, see ToUInt16(IFormatProvider). 有关此成员的说明，请参见 ToUInt32(IFormatProvider)。For a description of this member, see ToUInt32(IFormatProvider). 有关此成员的说明，请参见 ToUInt64(IFormatProvider)。For a description of this member, see ToUInt64(IFormatProvider).