# Single 結構

## 定義

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.Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
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
[<System.Serializable>]
type single = struct
interface IFormattable
interface IConvertible
[<System.Serializable>]
[<System.Runtime.InteropServices.ComVisible(true)>]
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

Single

## 備註

Single 值型別代表單一精確度的32位數位，其值範圍從負面的 3.402823 3.402823 e 38 到正面的 3.402823 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:

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;
}
}
// 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
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 很重要，請使用型別 BigIntegerWhen 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];
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 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];
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 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. Single轉換成看似相等的值 Double 通常不會 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.

警告

Single.Epsilon 測試是否相等時，有時會用來做為兩個值之間的距離的絕對量值 SingleSingle.Epsilon is sometimes used as an absolute measure of the distance between two Single values when testing for equality. 但是， Single.Epsilon 測量的最小可能值為零，可新增至或從中減去的值 SingleHowever, 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. 溢位的作業結果為 Single.MaxValue ，而溢位的作業結果為 PositiveInfinity Single.MinValue NegativeInfinity ，如下列範例所示。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.

• 如果浮點運算無效，運算的結果就是 NaNIf 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.NaNAny 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 值轉換成非 a 之任何基本數值資料類型的值， 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 OverflowException例外狀況，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 會先將值轉換為， Double 再執行比較。If one of the operands is a Double, the Single value is converted to a Double before performing the comparison. 如果其中一個運算元是整數類資料類型，則會先將它轉換成， Single 再執行比較。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.

警告

因為精確度差異， 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. 如需比較兩個值的詳細資訊，請參閱 測試是否相等 一節 SingleSee 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) 指令而非方法所執行 SingleCommon 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.

您可以藉由在 static Shared 類別的 Visual Basic) 方法中呼叫 (，來執行其他數學運算 System.MathYou can perform other mathematical operations by calling static (Shared in Visual Basic) methods in the System.Math class. 這些包括通常用於算術 (的其他方法，例如 Math.Abs 、和 Math.Sign Math.Sqrt) 、幾何 (例如 Math.CosMath.Sin) ，以及 (等微積分) Math.LogThese 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.

您也可以操控值中的個別位 SingleYou 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 方法，您也可以 Single 在32位整數中保留值的位模式。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. 您可以藉 Single 由呼叫方法來舍入值 Math.RoundYou 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. 您可以藉 Single 由呼叫 ToString 方法或使用 複合格式 功能，將值轉換成其字串表示。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. 您可以藉 Single 由呼叫或方法，將浮點值的字串表示轉換為值 Parse TryParseYou can convert the string representation of a floating-point value to a Single value by calling the Parse or TryParse method. 如果剖析作業失敗，則方法會擲回 Parse 例外狀況，而方法則會傳回 TryParse falseIf 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. 語言編譯器也支援隱含轉換所有其他標準數數值型別的值，但轉換 DoubleSingle 值除外。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位和類型的有效位數差異 DoubleThe 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

精確度最頻繁的問題會影響 Single 轉換成值的值 DoubleThe problem of precision most frequently affects Single values that are converted to Double values. 在下列範例中，相同除法運算所產生的兩個值不相等，因為其中一個值是轉換成的單精確度浮點值 DoubleIn 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

## 欄位

 代表大於零的最小正 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.

## 方法

 比較這個執行個體與特定物件，並且傳回一個整數，指出這個執行個體的值是小於、等於或大於特定物件的值。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.

## 運算子

 傳回值，該值表示兩個指定的 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.

## 明確介面實作

 將目前的執行個體與相同類型的另一個物件相比較，並傳回整數，這個整數表示目前的執行個體在排序次序中，位於另一個物件之前、之後或相同位置。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).