Convert.ToDecimal Метод

Определение

Преобразует заданное значение в десятичное число.

Перегрузки

ToDecimal(Single)

Преобразует значение заданного числа с плавающей запятой одиночной точности в эквивалентное десятичное число.

ToDecimal(String)

Преобразует заданное строковое представление числа в эквивалентное десятичное число.

ToDecimal(UInt16)

Преобразует значение заданного 16-разрядного целого числа без знака в эквивалентное десятичное число.

ToDecimal(String, IFormatProvider)

Преобразует заданное строковое представление числа в эквивалентное десятичное число, учитывая указанные сведения об особенностях форматирования, связанных с языком и региональными параметрами.

ToDecimal(UInt64)

Преобразует значение заданного 64-разрядного целого числа без знака в эквивалентное десятичное число.

ToDecimal(Object, IFormatProvider)

Преобразует значение заданного объекта в эквивалентное десятичное число, используя указанные сведения об особенностях форматирования, связанных с языком и региональными параметрами.

ToDecimal(SByte)

Преобразует значение заданного 8-разрядного знакового целого числа в эквивалентное десятичное число.

ToDecimal(UInt32)

Преобразует значение заданного 32-разрядного целого числа без знака в эквивалентное десятичное число.

ToDecimal(Object)

Преобразует значение заданного объекта в эквивалентное десятичное число.

ToDecimal(Int64)

Преобразует значение заданного 64-разрядного знакового целого числа в эквивалентное десятичное число.

ToDecimal(Int32)

Преобразует значение заданного 32-разрядного знакового целого числа в эквивалентное десятичное число.

ToDecimal(Int16)

Преобразует значение заданного 16-разрядного знакового целого числа в эквивалентное десятичное число.

ToDecimal(Double)

Преобразует значение заданного числа с плавающей запятой двойной точности в эквивалентное десятичное число.

ToDecimal(Decimal)

Возвращает заданное десятичное число; фактическое преобразование не производится.

ToDecimal(DateTime)

При вызове этого метода всегда возникает исключение InvalidCastException.

ToDecimal(Char)

При вызове этого метода всегда возникает исключение InvalidCastException.

ToDecimal(Byte)

Преобразует значение заданного 8-разрядного целого число без знака в эквивалентное десятичное число.

ToDecimal(Boolean)

Преобразует заданное логическое значение в эквивалентное десятичное число.

ToDecimal(Single)

Исходный код:
Convert.cs
Исходный код:
Convert.cs
Исходный код:
Convert.cs

Преобразует значение заданного числа с плавающей запятой одиночной точности в эквивалентное десятичное число.

public:
 static System::Decimal ToDecimal(float value);
public static decimal ToDecimal (float value);
static member ToDecimal : single -> decimal
Public Shared Function ToDecimal (value As Single) As Decimal

Параметры

value
Single

Число с плавающей запятой одиночной точности, которое нужно преобразовать.

Возвращаемое значение

Десятичное число, которое эквивалентно значению value.

Исключения

value Значение больше Decimal.MaxValue или меньше Decimal.MinValue.

Примеры

В следующем примере каждый элемент массива значений Single пытается преобразовать в Decimal значение.

float[] numbers = { Single.MinValue, -3e10f, -1093.54f, 0f, 1e-03f,
                    1034.23f, Single.MaxValue };
decimal result;

foreach (float number in numbers)
{
   try {
      result = Convert.ToDecimal(number);
      Console.WriteLine("Converted the Single value {0} to {1}.", number, result);
   }
   catch (OverflowException) {
      Console.WriteLine("{0} is out of range of the Decimal type.", number);
   }
}
// The example displays the following output:
//       -3.402823E+38 is out of range of the Decimal type.
//       Converted the Single value -3E+10 to -30000000000.
//       Converted the Single value -1093.54 to -1093.54.
//       Converted the Single value 0 to 0.
//       Converted the Single value 0.001 to 0.001.
//       Converted the Single value 1034.23 to 1034.23.
//       3.402823E+38 is out of range of the Decimal type.
let numbers =
    [| Single.MinValue; -3e10f; -1093.54f; 0f
       1e-03f; 1034.23f; Single.MaxValue |]

for number in numbers do
    try
        let result = Convert.ToDecimal number
        printfn $"Converted the Single value {number} to {result}."
    with :? OverflowException ->
        printfn $"{number} is out of range of the Decimal type."
// The example displays the following output:
//       -3.402823E+38 is out of range of the Decimal type.
//       Converted the Single value -3E+10 to -30000000000.
//       Converted the Single value -1093.54 to -1093.54.
//       Converted the Single value 0 to 0.
//       Converted the Single value 0.001 to 0.001.
//       Converted the Single value 1034.23 to 1034.23.
//       3.402823E+38 is out of range of the Decimal type.
Dim numbers() As Single = { Single.MinValue, -3e10, -1093.54, 0, 1e-03, _
                            1034.23, Single.MaxValue }
Dim result As Decimal

For Each number As Single In numbers
   Try
      result = Convert.ToDecimal(number)
      Console.WriteLine("Converted the Single value {0} to {1}.", number, result)
   Catch e As OverflowException
      Console.WriteLine("{0} is out of range of the Decimal type.", number)
   End Try
Next                                  
' The example displays the following output:
'       -3.402823E+38 is out of range of the Decimal type.
'       Converted the Single value -3E+10 to -30000000000.
'       Converted the Single value -1093.54 to -1093.54.
'       Converted the Single value 0 to 0.
'       Converted the Single value 0.001 to 0.001.
'       Converted the Single value 1034.23 to 1034.23.
'       3.402823E+38 is out of range of the Decimal type.

Комментарии

Значение Decimal , возвращаемое этим методом, содержит не более семи значимых цифр. value Если параметр содержит более семи значащими цифрами, он округляется с помощью округления до ближайшего. В следующем примере показано, как ToDecimal(Single) метод использует округление до ближайшего Decimal для возврата значения с семью значащими цифрами.

Console.WriteLine(Convert.ToDecimal(1234567500.12F));  // Displays 1234568000
Console.WriteLine(Convert.ToDecimal(1234568500.12F));  // Displays 1234568000

Console.WriteLine(Convert.ToDecimal(10.980365F));      // Displays 10.98036
Console.WriteLine(Convert.ToDecimal(10.980355F));      // Displays 10.98036
printfn $"{Convert.ToDecimal 1234567500.12F}"  // Displays 1234568000
printfn $"{Convert.ToDecimal 1234568500.12F}"  // Displays 1234568000

printfn $"{Convert.ToDecimal 10.980365F}"      // Displays 10.98036
printfn $"{Convert.ToDecimal 10.980355F}"      // Displays 10.98036
Console.WriteLine(Convert.ToDecimal(1234567500.12f))   ' Displays 1234568000
Console.WriteLine(Convert.ToDecimal(1234568500.12f))   ' Displays 1234568000

Console.WriteLine(Convert.ToDecimal(10.980365f))       ' Displays 10.98036 
Console.WriteLine(Convert.ToDecimal(10.980355f))       ' Displays 10.98036

См. также раздел

Применяется к

ToDecimal(String)

Исходный код:
Convert.cs
Исходный код:
Convert.cs
Исходный код:
Convert.cs

Преобразует заданное строковое представление числа в эквивалентное десятичное число.

public:
 static System::Decimal ToDecimal(System::String ^ value);
public static decimal ToDecimal (string value);
public static decimal ToDecimal (string? value);
static member ToDecimal : string -> decimal
Public Shared Function ToDecimal (value As String) As Decimal

Параметры

value
String

Строка, содержащая преобразуемое число.

Возвращаемое значение

Десятичное число, эквивалентное числу value, или 0 (нуль), если value равняется null.

Исключения

value не является числом в допустимом формате.

value представляет число, которое меньше Decimal.MinValue или больше Decimal.MaxValue.

Примеры

В следующем примере демонстрируется применение ToDecimal. Он пытается преобразовать String в Decimalи создает возможные исключения, которые могут возникнуть во время преобразования.

public:
   void ConvertStringDecimal( String^ stringVal )
   {
      Decimal decimalVal = 0;

      try
      {
         decimalVal = System::Convert::ToDecimal( stringVal );
         System::Console::WriteLine( "The String as a decimal is {0}.",
         decimalVal );
      }
      catch ( System::OverflowException^ ) 
      {
         System::Console::WriteLine(
            "The conversion from String to decimal overflowed." );
      }
      catch ( System::FormatException^ ) 
      {
         System::Console::WriteLine(
            "The String is not formatted as a decimal." );
      }
      catch ( System::ArgumentNullException^ ) 
      {
         System::Console::WriteLine( "The String is 0." );
      }
      
      // Decimal to String conversion will not overflow.
      stringVal = System::Convert::ToString( decimalVal );
      System::Console::WriteLine(
         "The decimal as a String is {0}.", stringVal );
   }
public void ConvertStringDecimal(string stringVal) {
    decimal decimalVal = 0;
    
    try {
        decimalVal = System.Convert.ToDecimal(stringVal);
        System.Console.WriteLine(
            "The string as a decimal is {0}.", decimalVal);
    }
    catch (System.OverflowException){
        System.Console.WriteLine(
            "The conversion from string to decimal overflowed.");
    }
    catch (System.FormatException) {
        System.Console.WriteLine(
            "The string is not formatted as a decimal.");
    }
    catch (System.ArgumentNullException) {
        System.Console.WriteLine(
            "The string is null.");
    }

    // Decimal to string conversion will not overflow.
    stringVal = System.Convert.ToString(decimalVal);
    System.Console.WriteLine(
        "The decimal as a string is {0}.", stringVal);
}
let convertStringDecimal (stringVal: string) =
    let decimalVal = 0m

    try
        let decimalVal = Convert.ToDecimal(stringVal)
        printfn $"The string as a decimal is {decimalVal}."
    with
    | :? OverflowException ->
        printfn "The conversion from string to decimal overflowed."
    | :? FormatException ->
        printfn "The string is not formatted as a decimal."
    | :? ArgumentNullException ->
        printfn "The string is null."

    // Decimal to string conversion will not overflow.
    let stringVal = Convert.ToString decimalVal
    printfn $"The decimal as a string is {stringVal}."
Public Sub ConvertStringDecimal(ByVal stringVal As String)
    Dim decimalVal As Decimal = 0

    Try
        decimalVal = System.Convert.ToDecimal(stringVal)
        System.Console.WriteLine("The string as a decimal is {0}.", _
                                  decimalVal)
    Catch exception As System.OverflowException
        System.Console.WriteLine( _
            "Overflow in string-to-decimal conversion.")
    Catch exception As System.FormatException
        System.Console.WriteLine( _
            "The string is not formatted as a decimal.")
    Catch exception As System.ArgumentException
        System.Console.WriteLine("The string is null.")
    End Try

    ' Decimal to string conversion will not overflow.
    stringVal = System.Convert.ToString(decimalVal)
    System.Console.WriteLine("The decimal as a string is {0}.", _
                              stringVal)
End Sub

Комментарии

ToDecimal(String) Использование метода эквивалентно передаче value в Decimal.Parse(String) метод . value интерпретируется с помощью соглашений о форматировании текущего языка и региональных параметров.

Если вы предпочитаете не обрабатывать исключение в случае сбоя преобразования, вместо этого можно вызвать Decimal.TryParse метод . Он возвращает Boolean значение, указывающее, успешно ли выполнено преобразование.

Применяется к

ToDecimal(UInt16)

Исходный код:
Convert.cs
Исходный код:
Convert.cs
Исходный код:
Convert.cs

Важно!

Этот API несовместим с CLS.

Преобразует значение заданного 16-разрядного целого числа без знака в эквивалентное десятичное число.

public:
 static System::Decimal ToDecimal(System::UInt16 value);
[System.CLSCompliant(false)]
public static decimal ToDecimal (ushort value);
[<System.CLSCompliant(false)>]
static member ToDecimal : uint16 -> decimal
Public Shared Function ToDecimal (value As UShort) As Decimal

Параметры

value
UInt16

16-разрядное целое число без знака для преобразования.

Возвращаемое значение

Десятичное число, которое эквивалентно значению value.

Атрибуты

Примеры

В следующем примере массив 16-разрядных целых чисел без знака преобразуется Decimal в значения.

ushort[] numbers = { UInt16.MinValue, 121, 12345, UInt16.MaxValue };
decimal result;

foreach (ushort number in numbers)
{
   result = Convert.ToDecimal(number);
   Console.WriteLine("Converted the UInt16 value {0} to {1}.",
                     number, result);
}
// The example displays the following output:
//       Converted the UInt16 value 0 to 0.
//       Converted the UInt16 value 121 to 121.
//       Converted the UInt16 value 12345 to 12345.
//       Converted the UInt16 value 65535 to 65535.
let numbers = 
    [| UInt16.MinValue; 121us; 12345us; UInt16.MaxValue |]

for number in numbers do
    let result = Convert.ToDecimal number
    printfn $"Converted the UInt16 value {number} to {result}."
// The example displays the following output:
//       Converted the UInt16 value 0 to 0.
//       Converted the UInt16 value 121 to 121.
//       Converted the UInt16 value 12345 to 12345.
//       Converted the UInt16 value 65535 to 65535.
Dim numbers() As UShort = { UInt16.MinValue, 121, 12345, UInt16.MaxValue }
Dim result As Decimal

For Each number As UShort In numbers
   result = Convert.ToDecimal(number)
   Console.WriteLine("Converted the UInt16 value {0} to {1}.", _
                     number, result)
Next   
' The example displays the following output:
'       Converted the UInt16 value 0 to 0.
'       Converted the UInt16 value 121 to 121.
'       Converted the UInt16 value 12345 to 12345.
'       Converted the UInt16 value 65535 to 65535.

См. также раздел

Применяется к

ToDecimal(String, IFormatProvider)

Исходный код:
Convert.cs
Исходный код:
Convert.cs
Исходный код:
Convert.cs

Преобразует заданное строковое представление числа в эквивалентное десятичное число, учитывая указанные сведения об особенностях форматирования, связанных с языком и региональными параметрами.

public:
 static System::Decimal ToDecimal(System::String ^ value, IFormatProvider ^ provider);
public static decimal ToDecimal (string value, IFormatProvider provider);
public static decimal ToDecimal (string? value, IFormatProvider? provider);
static member ToDecimal : string * IFormatProvider -> decimal
Public Shared Function ToDecimal (value As String, provider As IFormatProvider) As Decimal

Параметры

value
String

Строка, содержащая преобразуемое число.

provider
IFormatProvider

Объект, предоставляющий сведения о форматировании для определенного языка и региональных параметров.

Возвращаемое значение

Десятичное число, эквивалентное числу value, или 0 (нуль), если value равняется null.

Исключения

value не является числом в допустимом формате.

value представляет число, которое меньше Decimal.MinValue или больше Decimal.MaxValue.

Примеры

В следующем примере предпринимается попытка преобразовать массив строк в Decimal значения с помощью NumberFormatInfo объектов, представляющих два разных языка и региональных параметров.

using System;
using System.Globalization;

public class Example
{
   public static void Main()
   {
      string[] values = { "123456789", "12345.6789", "12 345,6789",
                          "123,456.789", "123 456,789", "123,456,789.0123",
                          "123 456 789,0123" };
      CultureInfo[] cultures = { new CultureInfo("en-US"),
                                 new CultureInfo("fr-FR") };

      foreach (CultureInfo culture in cultures)
      {
         Console.WriteLine("String -> Decimal Conversion Using the {0} Culture",
                           culture.Name);
         foreach (string value in values)
         {
            Console.Write("{0,20}  ->  ", value);
            try {
               Console.WriteLine(Convert.ToDecimal(value, culture));
            }
            catch (FormatException) {
               Console.WriteLine("FormatException");
            }
         }
         Console.WriteLine();
      }
   }
}
// The example displays the following output:
//       String -> Decimal Conversion Using the en-US Culture
//                  123456789  ->  123456789
//                 12345.6789  ->  12345.6789
//                12 345,6789  ->  FormatException
//                123,456.789  ->  123456.789
//                123 456,789  ->  FormatException
//           123,456,789.0123  ->  123456789.0123
//           123 456 789,0123  ->  FormatException
//
//       String -> Decimal Conversion Using the fr-FR Culture
//                  123456789  ->  123456789
//                 12345.6789  ->  FormatException
//                12 345,6789  ->  12345.6789
//                123,456.789  ->  FormatException
//                123 456,789  ->  123456.789
//           123,456,789.0123  ->  FormatException
//           123 456 789,0123  ->  123456789.0123
open System
open System.Globalization

let values = 
    [| "123456789"; "12345.6789"; "12 345,6789"; "123,456.789"
       "123 456,789"; "123,456,789.0123"; "123 456 789,0123" |]
let cultures = 
    [ CultureInfo "en-US"; CultureInfo "fr-FR" ]

for culture in cultures do
    printfn $"String -> Decimal Conversion Using the {culture.Name} Culture"
    for value in values do
        printf $"{value,20}  ->  "
        try
            printfn $"{Convert.ToDecimal(value, culture)}"
        with :? FormatException ->
            printfn "FormatException"
    printfn ""
// The example displays the following output:
//       String -> Decimal Conversion Using the en-US Culture
//                  123456789  ->  123456789
//                 12345.6789  ->  12345.6789
//                12 345,6789  ->  FormatException
//                123,456.789  ->  123456.789
//                123 456,789  ->  FormatException
//           123,456,789.0123  ->  123456789.0123
//           123 456 789,0123  ->  FormatException
//
//       String -> Decimal Conversion Using the fr-FR Culture
//                  123456789  ->  123456789
//                 12345.6789  ->  FormatException
//                12 345,6789  ->  12345.6789
//                123,456.789  ->  FormatException
//                123 456,789  ->  123456.789
//           123,456,789.0123  ->  FormatException
//           123 456 789,0123  ->  123456789.0123
Imports System.Globalization

Module Example
   Public Sub Main()
      Dim values() As String = { "123456789", "12345.6789", "12 345,6789", _
                                 "123,456.789", "123 456,789", "123,456,789.0123", _
                                 "123 456 789,0123" }
      Dim cultures() As CultureInfo = { New CultureInfo("en-US"), _
                                        New CultureInfo("fr-FR") } 

      For Each culture As CultureInfo In cultures
         Console.WriteLine("String -> Decimal Conversion Using the {0} Culture", _
                           culture.Name)
         For Each value As String In values
            Console.Write("{0,20}  ->  ", value)
            Try
               Console.WriteLine(Convert.ToDecimal(value, culture))
            Catch e As FormatException
               Console.WriteLine("FormatException")
            End Try   
         Next
         Console.WriteLine()
      Next                     
   End Sub
End Module
' The example displays the following output:
'       String -> Decimal Conversion Using the en-US Culture
'                  123456789  ->  123456789
'                 12345.6789  ->  12345.6789
'                12 345,6789  ->  FormatException
'                123,456.789  ->  123456.789
'                123 456,789  ->  FormatException
'           123,456,789.0123  ->  123456789.0123
'           123 456 789,0123  ->  FormatException
'       
'       String -> Decimal Conversion Using the fr-FR Culture
'                  123456789  ->  123456789
'                 12345.6789  ->  FormatException
'                12 345,6789  ->  12345.6789
'                123,456.789  ->  FormatException
'                123 456,789  ->  123456.789
'           123,456,789.0123  ->  FormatException
'           123 456 789,0123  ->  123456789.0123

Комментарии

Возвращаемое значение является результатом вызова метода в Decimal.Parsevalue.

providerIFormatProvider— это экземпляр, который получает NumberFormatInfo объект . Объект NumberFormatInfo предоставляет сведения о формате value. Если provider имеет значение null, NumberFormatInfo используется для текущего языка и региональных параметров.

Если вы предпочитаете не обрабатывать исключение в случае сбоя преобразования, вместо этого можно вызвать Decimal.TryParse метод . Он возвращает Boolean значение, указывающее, успешно ли выполнено преобразование.

Применяется к

ToDecimal(UInt64)

Исходный код:
Convert.cs
Исходный код:
Convert.cs
Исходный код:
Convert.cs

Важно!

Этот API несовместим с CLS.

Преобразует значение заданного 64-разрядного целого числа без знака в эквивалентное десятичное число.

public:
 static System::Decimal ToDecimal(System::UInt64 value);
[System.CLSCompliant(false)]
public static decimal ToDecimal (ulong value);
[<System.CLSCompliant(false)>]
static member ToDecimal : uint64 -> decimal
Public Shared Function ToDecimal (value As ULong) As Decimal

Параметры

value
UInt64

64-разрядное целое число без знака для преобразования.

Возвращаемое значение

Десятичное число, которое эквивалентно значению value.

Атрибуты

Примеры

В следующем примере массив длинных целых чисел без знака преобразуется Decimal в значения.

ulong[] numbers = { UInt64.MinValue, 121, 12345, UInt64.MaxValue };
decimal result;

foreach (ulong number in numbers)
{
   result = Convert.ToDecimal(number);
   Console.WriteLine("Converted the UInt64 value {0} to {1}.",
                     number, result);
}
// The example displays the following output:
//    Converted the UInt64 value 0 to 0.
//    Converted the UInt64 value 121 to 121.
//    Converted the UInt64 value 12345 to 12345.
//    Converted the UInt64 value 18446744073709551615 to 18446744073709551615.
let numbers = 
    [| UInt64.MinValue; 121uL; 12345uL; UInt64.MaxValue |]

for number in numbers do
    let result = Convert.ToDecimal number
    printfn $"Converted the UInt64 value {number} to {result}."
// The example displays the following output:
//    Converted the UInt64 value 0 to 0.
//    Converted the UInt64 value 121 to 121.
//    Converted the UInt64 value 12345 to 12345.
//    Converted the UInt64 value 18446744073709551615 to 18446744073709551615.
Dim numbers() As ULong = { UInt64.MinValue, 121, 12345, UInt64.MaxValue }
Dim result As Decimal

For Each number As ULong In numbers
   result = Convert.ToDecimal(number)
   Console.WriteLine("Converted the UInt64 value {0} to {1}.", _
                     number, result)
Next   
' The example displays the following output:
'    Converted the UInt64 value 0 to 0.
'    Converted the UInt64 value 121 to 121.
'    Converted the UInt64 value 12345 to 12345.
'    Converted the UInt64 value 18446744073709551615 to 18446744073709551615.

См. также раздел

Применяется к

ToDecimal(Object, IFormatProvider)

Исходный код:
Convert.cs
Исходный код:
Convert.cs
Исходный код:
Convert.cs

Преобразует значение заданного объекта в эквивалентное десятичное число, используя указанные сведения об особенностях форматирования, связанных с языком и региональными параметрами.

public:
 static System::Decimal ToDecimal(System::Object ^ value, IFormatProvider ^ provider);
public static decimal ToDecimal (object value, IFormatProvider provider);
public static decimal ToDecimal (object? value, IFormatProvider? provider);
static member ToDecimal : obj * IFormatProvider -> decimal
Public Shared Function ToDecimal (value As Object, provider As IFormatProvider) As Decimal

Параметры

value
Object

Объект, реализующий интерфейс IConvertible.

provider
IFormatProvider

Объект, предоставляющий сведения о форматировании для определенного языка и региональных параметров.

Возвращаемое значение

Десятичное число, эквивалентное value, или 0 (нуль), если value равняется null.

Исключения

value имеет неправильный формат для типа Decimal.

value не реализует интерфейс IConvertible.

-или-

Преобразование не поддерживается.

value представляет число, которое меньше Decimal.MinValue или больше Decimal.MaxValue.

Примеры

В следующем примере определяется класс Temperature , реализующий интерфейс IConvertible .

using System;
using System.Globalization;

public class Temperature : IConvertible
{
   private decimal m_Temp;

   public Temperature(decimal temperature)
   {
      this.m_Temp = temperature;
   }

   public decimal Celsius
   {
      get { return this.m_Temp; }
   }

   public decimal Kelvin
   {
      get { return this.m_Temp + 273.15m; }
   }

   public decimal Fahrenheit
   {
      get { return Math.Round((decimal) (this.m_Temp * 9 / 5 + 32), 2); }
   }

   public override string ToString()
   {
      return m_Temp.ToString("N2") + " °C";
   }

   // IConvertible implementations.
   public TypeCode GetTypeCode()
   {
      return TypeCode.Object;
   }

   public bool ToBoolean(IFormatProvider provider)
   {
      if (m_Temp == 0)
         return false;
      else
         return true;
   }

   public byte ToByte(IFormatProvider provider)
   {
      if (m_Temp < Byte.MinValue || m_Temp > Byte.MaxValue)
         throw new OverflowException(String.Format("{0} is out of range of the Byte type.",
                                                   this.m_Temp));
      else
         return Decimal.ToByte(this.m_Temp);
   }

   public char ToChar(IFormatProvider provider)
   {
      throw new InvalidCastException("Temperature to Char conversion is not supported.");
   }

   public DateTime ToDateTime(IFormatProvider provider)
   {
      throw new InvalidCastException("Temperature to DateTime conversion is not supported.");
   }

   public decimal ToDecimal(IFormatProvider provider)
   {
      return this.m_Temp;
   }

   public double ToDouble(IFormatProvider provider)
   {
      return Decimal.ToDouble(this.m_Temp);
   }

   public short ToInt16(IFormatProvider provider)
   {
      if (this.m_Temp < Int16.MinValue || this.m_Temp > Int16.MaxValue)
         throw new OverflowException(String.Format("{0} is out of range of the Int16 type.",
                                                   this.m_Temp));
      else
         return Decimal.ToInt16(this.m_Temp);
   }

   public int ToInt32(IFormatProvider provider)
      {
      if (this.m_Temp < Int32.MinValue || this.m_Temp > Int32.MaxValue)
         throw new OverflowException(String.Format("{0} is out of range of the Int32 type.",
                                                   this.m_Temp));
      else
         return Decimal.ToInt32(this.m_Temp);
   }

   public long ToInt64(IFormatProvider provider)
   {
      if (this.m_Temp < Int64.MinValue || this.m_Temp > Int64.MaxValue)
         throw new OverflowException(String.Format("{0} is out of range of the Int64 type.",
                                                   this.m_Temp));
      else
         return Decimal.ToInt64(this.m_Temp);
   }

   public sbyte ToSByte(IFormatProvider provider)
   {
      if (this.m_Temp < SByte.MinValue || this.m_Temp > SByte.MaxValue)
         throw new OverflowException(String.Format("{0} is out of range of the SByte type.",
                                                   this.m_Temp));
      else
         return Decimal.ToSByte(this.m_Temp);
   }

   public float ToSingle(IFormatProvider provider)
   {
      return Decimal.ToSingle(this.m_Temp);
   }

   public string ToString(IFormatProvider provider)
   {
      return m_Temp.ToString("N2", provider) + " °C";
   }

   public object ToType(Type conversionType, IFormatProvider provider)
   {
      switch (Type.GetTypeCode(conversionType))
      {
         case TypeCode.Boolean:
            return this.ToBoolean(null);
         case TypeCode.Byte:
            return this.ToByte(null);
         case TypeCode.Char:
            return this.ToChar(null);
         case TypeCode.DateTime:
            return this.ToDateTime(null);
         case TypeCode.Decimal:
            return this.ToDecimal(null);
         case TypeCode.Double:
            return this.ToDouble(null);
         case TypeCode.Int16:
            return this.ToInt16(null);
         case TypeCode.Int32:
            return this.ToInt32(null);
         case TypeCode.Int64:
            return this.ToInt64(null);
         case TypeCode.Object:
            if (typeof(Temperature).Equals(conversionType))
               return this;
            else
               throw new InvalidCastException(String.Format("Conversion to a {0} is not supported.",
                                                            conversionType.Name));
         case TypeCode.SByte:
            return this.ToSByte(null);
         case TypeCode.Single:
            return this.ToSingle(null);
         case TypeCode.String:
            return this.ToString(provider);
         case TypeCode.UInt16:
            return this.ToUInt16(null);
         case TypeCode.UInt32:
            return this.ToUInt32(null);
         case TypeCode.UInt64:
            return this.ToUInt64(null);
         default:
            throw new InvalidCastException(String.Format("Conversion to {0} is not supported.", conversionType.Name));
      }
   }

   public ushort ToUInt16(IFormatProvider provider)
   {
      if (this.m_Temp < UInt16.MinValue || this.m_Temp > UInt16.MaxValue)
         throw new OverflowException(String.Format("{0} is out of range of the UInt16 type.",
                                                   this.m_Temp));
      else
         return Decimal.ToUInt16(this.m_Temp);
   }

   public uint ToUInt32(IFormatProvider provider)
   {
      if (this.m_Temp < UInt32.MinValue || this.m_Temp > UInt32.MaxValue)
         throw new OverflowException(String.Format("{0} is out of range of the UInt32 type.",
                                                   this.m_Temp));
      else
         return Decimal.ToUInt32(this.m_Temp);
   }

   public ulong ToUInt64(IFormatProvider provider)
   {
      if (this.m_Temp < UInt64.MinValue || this.m_Temp > UInt64.MaxValue)
         throw new OverflowException(String.Format("{0} is out of range of the UInt64 type.",
                                                   this.m_Temp));
      else
         return Decimal.ToUInt64(this.m_Temp);
   }
}
open System
open System.Globalization

type Temperature(temperature) =
    member _.Celsius = temperature

    member _.Kelvin =
        temperature + 273.15m

    member _.Fahrenheit =
        Math.Round(temperature * 9m / 5m + 32m, 2)

    override _.ToString() =
        $"{temperature:N2} °C"

    // IConvertible implementations.
    interface IConvertible with
        member _.GetTypeCode() =
            TypeCode.Object

        member _.ToBoolean(provider: IFormatProvider) =
            temperature <> 0M

        member _.ToByte(provider: IFormatProvider) =
            if uint8 temperature < Byte.MinValue || uint8 temperature > Byte.MaxValue then
                raise (OverflowException $"{temperature} is out of range of the Byte type.")
            else
            Decimal.ToByte temperature

        member _.ToChar(provider: IFormatProvider) =
            raise (InvalidCastException "Temperature to Char conversion is not supported.")

        member _.ToDateTime(provider: IFormatProvider) =
            raise (InvalidCastException "Temperature to DateTime conversion is not supported.")

        member _.ToDecimal(provider: IFormatProvider) =
            temperature

        member _.ToDouble(provider: IFormatProvider) =
            Decimal.ToDouble temperature

        member _.ToInt16(provider: IFormatProvider) =
            if int16 temperature < Int16.MinValue || int16 temperature > Int16.MaxValue then
                raise (OverflowException $"{temperature} is out of range of the Int16 type.")
            else
                Decimal.ToInt16 temperature

        member _.ToInt32(provider: IFormatProvider) =
            if int temperature < Int32.MinValue || int temperature > Int32.MaxValue then
                raise (OverflowException $"{temperature} is out of range of the Int32 type.")
            else
                Decimal.ToInt32 temperature

        member _.ToInt64(provider: IFormatProvider) =
            if int64 temperature < Int64.MinValue || int64 temperature > Int64.MaxValue then
                raise (OverflowException $"{temperature} is out of range of the Int64 type.")
            else
                Decimal.ToInt64 temperature

        member _.ToSByte(provider: IFormatProvider) =
            if int8 temperature < SByte.MinValue || int8 temperature > SByte.MaxValue then
                raise (OverflowException $"{temperature} is out of range of the SByte type.")
            else
                Decimal.ToSByte temperature

        member _.ToSingle(provider: IFormatProvider) =
            Decimal.ToSingle temperature

        member _.ToString(provider: IFormatProvider) =
           temperature.ToString("N2", provider) + " °C"

        member this.ToType(conversionType: Type, provider: IFormatProvider) =
            let this = this :> IConvertible
            match Type.GetTypeCode conversionType with
            | TypeCode.Boolean ->
                this.ToBoolean null
            | TypeCode.Byte ->
                this.ToByte null
            | TypeCode.Char ->
                this.ToChar null
            | TypeCode.DateTime ->
                this.ToDateTime null
            | TypeCode.Decimal ->
                this.ToDecimal null
            | TypeCode.Double ->
                this.ToDouble null
            | TypeCode.Int16 ->
                this.ToInt16 null
            | TypeCode.Int32 ->
                this.ToInt32 null
            | TypeCode.Int64 ->
                this.ToInt64 null
            | TypeCode.Object ->
                if typeof<Temperature>.Equals conversionType then
                    this
                else
                    raise (InvalidCastException $"Conversion to a {conversionType.Name} is not supported.")
            | TypeCode.SByte ->
                this.ToSByte null
            | TypeCode.Single ->
                this.ToSingle null
            | TypeCode.String ->
                this.ToString provider
            | TypeCode.UInt16 ->
                this.ToUInt16 null
            | TypeCode.UInt32 ->
                this.ToUInt32 null
            | TypeCode.UInt64 ->
                this.ToUInt64 null
            | _ ->
                raise (InvalidCastException $"Conversion to {conversionType.Name} is not supported.")

        member _.ToUInt16(provider: IFormatProvider) =
            if uint16 temperature < UInt16.MinValue || uint16 temperature > UInt16.MaxValue then
                raise (OverflowException $"{temperature} is out of range of the UInt16 type.")
            else
                Decimal.ToUInt16 temperature

        member _.ToUInt32(provider: IFormatProvider) =
            if uint temperature < UInt32.MinValue || uint temperature > UInt32.MaxValue then
                raise (OverflowException $"{temperature} is out of range of the UInt32 type.")
            else
                Decimal.ToUInt32 temperature

        member _.ToUInt64(provider: IFormatProvider) =
            if uint64 temperature < UInt64.MinValue || uint64 temperature > UInt64.MaxValue then
                raise (OverflowException $"{temperature} is out of range of the UInt64 type.")
            else
                Decimal.ToUInt64 temperature
Imports System.Globalization

Public Class Temperature : Implements IConvertible
   Private m_Temp As Decimal

   Public Sub New(temperature As Decimal)
      Me.m_Temp = temperature
   End Sub
   
   Public ReadOnly Property Celsius() As Decimal
      Get
         Return Me.m_Temp
      End Get   
   End Property
   
   Public ReadOnly Property Kelvin() As Decimal
      Get
         Return Me.m_Temp + 273.15d   
      End Get
   End Property
   
   Public ReadOnly Property Fahrenheit() As Decimal
      Get
         Return Math.Round(CDec(Me.m_Temp * 9 / 5 + 32), 2)
      End Get      
   End Property
   
   Public Overrides Function ToString() As String
      Return m_Temp.ToString("N2") & " °C"
   End Function

   ' IConvertible implementations.
   Public Function GetTypeCode() As TypeCode _
                   Implements IConvertible.GetTypeCode
      Return TypeCode.Object
   End Function
   
   Public Function ToBoolean(provider As IFormatProvider) As Boolean _
                   Implements IConvertible.ToBoolean
      If m_Temp = 0 Then
         Return False
      Else
         Return True
      End If
   End Function 
   
   Public Function ToByte(provider As IFormatProvider) As Byte _
                   Implements IConvertible.ToByte
      If m_Temp < Byte.MinValue Or m_Temp > Byte.MaxValue Then
         Throw New OverflowException(String.Format("{0} is out of range of the Byte type.", _ 
                                                   Me.m_Temp)) 
      Else
         Return Decimal.ToByte(Me.m_Temp)
      End If       
   End Function
   
   Public Function ToChar(provider As IFormatProvider) As Char _
                   Implements IConvertible.ToChar
      Throw New InvalidCastException("Temperature to Char conversion is not supported.")
   End Function 
   
   Public Function ToDateTime(provider As IFormatProvider) As Date _
                   Implements IConvertible.ToDateTime
      Throw New InvalidCastException("Temperature to DateTime conversion is not supported.")
   End Function
   
   Public Function ToDecimal(provider As IFormatProvider) As Decimal _
                   Implements IConvertible.ToDecimal
      Return Me.m_Temp
   End Function
   
   Public Function ToDouble(provider As IFormatProvider) As Double _
                   Implements IConvertible.ToDouble
      Return Decimal.ToDouble(Me.m_Temp)
   End Function   
   
   Public Function ToInt16(provider As IFormatProvider) As Int16 _
                   Implements IConvertible.ToInt16
      If Me.m_Temp < Int16.MinValue Or Me.m_Temp > Int16.MaxValue Then
         Throw New OverflowException(String.Format("{0} is out of range of the Int16 type.", _
                                                   Me.m_Temp))
      Else
         Return Decimal.ToInt16(Me.m_Temp)   
      End If
   End Function
   
   Public Function ToInt32(provider As IFormatProvider) As Int32 _
                   Implements IConvertible.ToInt32
      If Me.m_Temp < Int32.MinValue Or Me.m_Temp > Int32.MaxValue Then
         Throw New OverflowException(String.Format("{0} is out of range of the Int32 type.", _
                                                   Me.m_Temp))
      Else
         Return Decimal.ToInt32(Me.m_Temp)
      End If      
   End Function
   
   Public Function ToInt64(provider As IFormatProvider) As Int64 _
                   Implements IConvertible.ToInt64
      If Me.m_Temp < Int64.MinValue Or Me.m_Temp > Int64.MaxValue Then
         Throw New OverflowException(String.Format("{0} is out of range of the Int64 type.", _
                                                   Me.m_Temp))
      Else
         Return Decimal.ToInt64(Me.m_Temp)
      End If      
   End Function
   
   Public Function ToSByte(provider As IFormatProvider) As SByte _
                   Implements IConvertible.ToSByte
      If Me.m_Temp < SByte.MinValue Or Me.m_Temp > SByte.MaxValue Then
         Throw New OverflowException(String.Format("{0} is out of range of the SByte type.", _
                                                   Me.m_Temp))
      Else
         Return Decimal.ToSByte(Me.m_Temp)
      End If      
   End Function

   Public Function ToSingle(provider As IFormatProvider) As Single _
                   Implements IConvertible.ToSingle
      Return Decimal.ToSingle(Me.m_Temp)
   End Function

   Public Overloads Function ToString(provider As IFormatProvider) As String _
                   Implements IConvertible.ToString
      Return m_Temp.ToString("N2", provider) & " °C"
   End Function
   
   Public Function ToType(conversionType As Type, provider As IFormatProvider) As Object _
                   Implements IConvertible.ToType
      Select Case Type.GetTypeCode(conversionType)
         Case TypeCode.Boolean 
            Return Me.ToBoolean(Nothing)
         Case TypeCode.Byte
            Return Me.ToByte(Nothing)
         Case TypeCode.Char
            Return Me.ToChar(Nothing)
         Case TypeCode.DateTime
            Return Me.ToDateTime(Nothing)
         Case TypeCode.Decimal
            Return Me.ToDecimal(Nothing)
         Case TypeCode.Double
            Return Me.ToDouble(Nothing)
         Case TypeCode.Int16
            Return Me.ToInt16(Nothing)
         Case TypeCode.Int32
            Return Me.ToInt32(Nothing)
         Case TypeCode.Int64
            Return Me.ToInt64(Nothing)
         Case TypeCode.Object
            If GetType(Temperature).Equals(conversionType) Then
               Return Me
            Else
               Throw New InvalidCastException(String.Format("Conversion to a {0} is not supported.", _
                                                            conversionType.Name))
            End If 
         Case TypeCode.SByte
            Return Me.ToSByte(Nothing)
         Case TypeCode.Single
            Return Me.ToSingle(Nothing)
         Case TypeCode.String
            Return Me.ToString(provider)
         Case TypeCode.UInt16
            Return Me.ToUInt16(Nothing)
         Case TypeCode.UInt32
            Return Me.ToUInt32(Nothing)
         Case TypeCode.UInt64
            Return Me.ToUInt64(Nothing)   
         Case Else
            Throw New InvalidCastException(String.Format("Conversion to {0} is not supported.", conversionType.Name))   
      End Select
   End Function
   
   Public Function ToUInt16(provider As IFormatProvider) As UInt16 _
                   Implements IConvertible.ToUInt16
      If Me.m_Temp < UInt16.MinValue Or Me.m_Temp > UInt16.MaxValue Then
         Throw New OverflowException(String.Format("{0} is out of range of the UInt16 type.", _
                                                   Me.m_Temp))
      Else
         Return Decimal.ToUInt16(Me.m_Temp)
      End If   
   End Function

   Public Function ToUInt32(provider As IFormatProvider) As UInt32 _
                   Implements IConvertible.ToUInt32
      If Me.m_Temp < UInt32.MinValue Or Me.m_Temp > UInt32.MaxValue Then
         Throw New OverflowException(String.Format("{0} is out of range of the UInt32 type.", _
                                                   Me.m_Temp))
      Else
         Return Decimal.ToUInt32(Me.m_Temp)
      End If   
   End Function
   
   Public Function ToUInt64(provider As IFormatProvider) As UInt64 _
                   Implements IConvertible.ToUInt64
      If Me.m_Temp < UInt64.MinValue Or Me.m_Temp > UInt64.MaxValue Then
         Throw New OverflowException(String.Format("{0} is out of range of the UInt64 type.", _
                                                   Me.m_Temp))
      Else
         Return Decimal.ToUInt64(Me.m_temp)
      End If   
   End Function
End Class

В следующем примере показано, что при Temperature передаче объекта в качестве параметра ToDecimal(Object, IFormatProvider) в метод IConvertible.ToDecimal вызывается реализация Temperature класса для выполнения преобразования.

public class Example
{
   public static void Main()
   {
      Temperature cold = new Temperature(-40);
      Temperature freezing = new Temperature(0);
      Temperature boiling = new Temperature(100);

      Console.WriteLine(Convert.ToDecimal(cold, null));
      Console.WriteLine(Convert.ToDecimal(freezing, null));
      Console.WriteLine(Convert.ToDecimal(boiling, null));
   }
}
// The example dosplays the following output:
//       -40
//       0
//       100
let cold = Temperature -40
let freezing = Temperature 0
let boiling = Temperature 100

printfn $"{Convert.ToDecimal(cold, null)}"
printfn $"{Convert.ToDecimal(freezing, null)}"
printfn $"{Convert.ToDecimal(boiling, null)}"
// The example dosplays the following output:
//       -40
//       0
//       100
Module Example
   Public Sub Main()
      Dim cold As New Temperature(-40)
      Dim freezing As New Temperature(0)
      Dim boiling As New Temperature(100)
      
      Console.WriteLine(Convert.ToDecimal(cold, Nothing))
      Console.WriteLine(Convert.ToDecimal(freezing, Nothing))
      Console.WriteLine(Convert.ToDecimal(boiling, Nothing))
   End Sub
End Module
' The example displays the following output:
'       -40
'       0
'       100

Комментарии

Возвращаемое значение является результатом вызова IConvertible.ToDecimal метода базового типа value.

provider позволяет пользователю указать сведения о преобразовании для конкретного языка и региональных параметров для содержимого value. Базовые типы игнорируют provider; однако параметр можно использовать, если value является определяемым пользователем типом, реализующим IConvertible интерфейс .

См. также раздел

Применяется к

ToDecimal(SByte)

Исходный код:
Convert.cs
Исходный код:
Convert.cs
Исходный код:
Convert.cs

Важно!

Этот API несовместим с CLS.

Преобразует значение заданного 8-разрядного знакового целого числа в эквивалентное десятичное число.

public:
 static System::Decimal ToDecimal(System::SByte value);
[System.CLSCompliant(false)]
public static decimal ToDecimal (sbyte value);
[<System.CLSCompliant(false)>]
static member ToDecimal : sbyte -> decimal
Public Shared Function ToDecimal (value As SByte) As Decimal

Параметры

value
SByte

8-разрядное целое число со знаком для преобразования.

Возвращаемое значение

Десятичное число, которое эквивалентно значению value.

Атрибуты

Примеры

В следующем примере каждый элемент массива со знаком преобразуется в Decimal значение.

sbyte[] numbers = { SByte.MinValue, -23, 0, 17, SByte.MaxValue };
decimal result;

foreach (sbyte number in numbers)
{
   result = Convert.ToDecimal(number);
   Console.WriteLine("Converted the SByte value {0} to {1}.", number, result);
}
//       Converted the SByte value -128 to -128.
//       Converted the SByte value -23 to -23.
//       Converted the SByte value 0 to 0.
//       Converted the SByte value 17 to 17.
//       Converted the SByte value 127 to 127.
let numbers = 
    [| SByte.MinValue, -23, 0, 17, SByte.MaxValue |]

for number in numbers do
    let result = Convert.ToDecimal number
    printfn $"Converted the SByte value {number} to {result}."
//       Converted the SByte value -128 to -128.
//       Converted the SByte value -23 to -23.
//       Converted the SByte value 0 to 0.
//       Converted the SByte value 17 to 17.
//       Converted the SByte value 127 to 127.
Dim numbers() As SByte = { SByte.MinValue, -23, 0, 17, SByte.MaxValue }
Dim result As Decimal

For Each number As SByte In numbers
   result = Convert.ToDecimal(number)
   Console.WriteLine("Converted the SByte value {0} to {1}.", number, result)
Next
'       Converted the SByte value -128 to -128.
'       Converted the SByte value -23 to -23.
'       Converted the SByte value 0 to 0.
'       Converted the SByte value 17 to 17.
'       Converted the SByte value 127 to 127.

См. также раздел

Применяется к

ToDecimal(UInt32)

Исходный код:
Convert.cs
Исходный код:
Convert.cs
Исходный код:
Convert.cs

Важно!

Этот API несовместим с CLS.

Преобразует значение заданного 32-разрядного целого числа без знака в эквивалентное десятичное число.

public:
 static System::Decimal ToDecimal(System::UInt32 value);
[System.CLSCompliant(false)]
public static decimal ToDecimal (uint value);
[<System.CLSCompliant(false)>]
static member ToDecimal : uint32 -> decimal
Public Shared Function ToDecimal (value As UInteger) As Decimal

Параметры

value
UInt32

32-разрядное целое число без знака для преобразования.

Возвращаемое значение

Десятичное число, которое эквивалентно значению value.

Атрибуты

Примеры

В следующем примере массив целых чисел без знака преобразуется Decimal в значения.

uint[] numbers = { UInt32.MinValue, 121, 12345, UInt32.MaxValue };
decimal result;

foreach (uint number in numbers)
{
   result = Convert.ToDecimal(number);
   Console.WriteLine("Converted the UInt32 value {0} to {1}.",
                     number, result);
}
// The example displays the following output:
//       Converted the UInt32 value 0 to 0.
//       Converted the UInt32 value 121 to 121.
//       Converted the UInt32 value 12345 to 12345.
//       Converted the UInt32 value 4294967295 to 4294967295.
let numbers =
    [| UInt32.MinValue; 121u; 12345u; UInt32.MaxValue |]

for number in numbers do
    let result = Convert.ToDecimal number
    printfn $"Converted the UInt32 value {number} to {result}."
// The example displays the following output:
//       Converted the UInt32 value 0 to 0.
//       Converted the UInt32 value 121 to 121.
//       Converted the UInt32 value 12345 to 12345.
//       Converted the UInt32 value 4294967295 to 4294967295.
Dim numbers() As UInteger = { UInt32.MinValue, 121, 12345, UInt32.MaxValue }
Dim result As Decimal

For Each number As UInteger In numbers
   result = Convert.ToDecimal(number)
   Console.WriteLine("Converted the UInt32 value {0} to {1}.", _
                     number, result)
Next   
' The example displays the following output:
'       Converted the UInt32 value 0 to 0.
'       Converted the UInt32 value 121 to 121.
'       Converted the UInt32 value 12345 to 12345.
'       Converted the UInt32 value 4294967295 to 4294967295.

См. также раздел

Применяется к

ToDecimal(Object)

Исходный код:
Convert.cs
Исходный код:
Convert.cs
Исходный код:
Convert.cs

Преобразует значение заданного объекта в эквивалентное десятичное число.

public:
 static System::Decimal ToDecimal(System::Object ^ value);
public static decimal ToDecimal (object value);
public static decimal ToDecimal (object? value);
static member ToDecimal : obj -> decimal
Public Shared Function ToDecimal (value As Object) As Decimal

Параметры

value
Object

Объект, реализующий интерфейс IConvertible, или значение null.

Возвращаемое значение

Десятичное число, эквивалентное value, или 0 (нуль), если value равняется null.

Исключения

value имеет неправильный формат для типа Decimal.

value не реализует интерфейс IConvertible.

-или-

Преобразование не поддерживается.

value представляет число, которое меньше Decimal.MinValue или больше Decimal.MaxValue.

Примеры

В следующем примере каждый элемент массива объектов пытается преобразовать в Decimal значение.

object[] values = { true, 'a', 123, 1.764e32, "9.78", "1e-02",
                    1.67e03, "A100", "1,033.67", DateTime.Now,
                    Double.MaxValue };
decimal result;

foreach (object value in values)
{
   try {
      result = Convert.ToDecimal(value);
      Console.WriteLine("Converted the {0} value {1} to {2}.",
                        value.GetType().Name, value, result);
   }
   catch (OverflowException) {
      Console.WriteLine("The {0} value {1} is out of range of the Decimal type.",
                        value.GetType().Name, value);
   }
   catch (FormatException) {
      Console.WriteLine("The {0} value {1} is not recognized as a valid Decimal value.",
                        value.GetType().Name, value);
   }
   catch (InvalidCastException) {
      Console.WriteLine("Conversion of the {0} value {1} to a Decimal is not supported.",
                        value.GetType().Name, value);
   }
}
// The example displays the following output:
//    Converted the Boolean value True to 1.
//    Conversion of the Char value a to a Decimal is not supported.
//    Converted the Int32 value 123 to 123.
//    The Double value 1.764E+32 is out of range of the Decimal type.
//    Converted the String value 9.78 to 9.78.
//    The String value 1e-02 is not recognized as a valid Decimal value.
//    Converted the Double value 1670 to 1670.
//    The String value A100 is not recognized as a valid Decimal value.
//    Converted the String value 1,033.67 to 1033.67.
//    Conversion of the DateTime value 10/15/2008 05:40:42 PM to a Decimal is not supported.
//    The Double value 1.79769313486232E+308 is out of range of the Decimal type.
let values: obj[] =
    [| true; 'a'; 123; 1.764e32; "9.78"; "1e-02"; 1.67e03
       "A100"; "1,033.67"; DateTime.Now; Double.MaxValue |]

for value in values do
    try
        let result = Convert.ToDecimal value
        printfn $"Converted the {value.GetType().Name} value {value} to {result}."
    with
    | :? OverflowException ->
        printfn $"The {value.GetType().Name} value {value} is out of range of the Decimal type."
    | :? FormatException ->
        printfn $"The {value.GetType().Name} value {value} is not recognized as a valid Decimal value."
    | :? InvalidCastException ->
        printfn $"Conversion of the {value.GetType().Name} value {value} to a Decimal is not supported."
// The example displays the following output:
//    Converted the Boolean value True to 1.
//    Conversion of the Char value a to a Decimal is not supported.
//    Converted the Int32 value 123 to 123.
//    The Double value 1.764E+32 is out of range of the Decimal type.
//    Converted the String value 9.78 to 9.78.
//    The String value 1e-02 is not recognized as a valid Decimal value.
//    Converted the Double value 1670 to 1670.
//    The String value A100 is not recognized as a valid Decimal value.
//    Converted the String value 1,033.67 to 1033.67.
//    Conversion of the DateTime value 10/15/2008 05:40:42 PM to a Decimal is not supported.
//    The Double value 1.79769313486232E+308 is out of range of the Decimal type.
Dim values() As Object = { True, "a"c, 123, 1.764e32, "9.78", "1e-02", _
                           1.67e03, "A100", "1,033.67", Date.Now, _
                           Double.MaxValue }   
Dim result As Decimal

For Each value As Object In values
   Try
      result = Convert.ToDecimal(value)
      Console.WriteLine("Converted the {0} value {1} to {2}.", _
                        value.GetType().Name, value, result)
   Catch e As OverflowException
      Console.WriteLine("The {0} value {1} is out of range of the Decimal type.", _
                        value.GetType().Name, value)
   Catch e As FormatException
      Console.WriteLine("The {0} value {1} is not recognized as a valid Decimal value.", _
                        value.GetType().Name, value)
   Catch e As InvalidCastException
      Console.WriteLine("Conversion of the {0} value {1} to a Decimal is not supported.", _
                        value.GetType().Name, value)
   End Try                     
Next
' The example displays the following output:
'    Converted the Boolean value True to 1.
'    Conversion of the Char value a to a Decimal is not supported.
'    Converted the Int32 value 123 to 123.
'    The Double value 1.764E+32 is out of range of the Decimal type.
'    Converted the String value 9.78 to 9.78.
'    The String value 1e-02 is not recognized as a valid Decimal value.
'    Converted the Double value 1670 to 1670.
'    The String value A100 is not recognized as a valid Decimal value.
'    Converted the String value 1,033.67 to 1033.67.
'    Conversion of the DateTime value 10/15/2008 05:40:42 PM to a Decimal is not supported.
'    The Double value 1.79769313486232E+308 is out of range of the Decimal type.

Комментарии

Возвращаемое значение является результатом вызова IConvertible.ToDecimal метода базового типа value.

См. также раздел

Применяется к

ToDecimal(Int64)

Исходный код:
Convert.cs
Исходный код:
Convert.cs
Исходный код:
Convert.cs

Преобразует значение заданного 64-разрядного знакового целого числа в эквивалентное десятичное число.

public:
 static System::Decimal ToDecimal(long value);
public static decimal ToDecimal (long value);
static member ToDecimal : int64 -> decimal
Public Shared Function ToDecimal (value As Long) As Decimal

Параметры

value
Int64

64-разрядное целое число со знаком для преобразования.

Возвращаемое значение

Десятичное число, которое эквивалентно значению value.

Примеры

В следующем примере значение преобразуется Int64 в Decimal значение .

public:
   void ConvertLongDecimal( Int64 longVal )
   {
      Decimal decimalVal;
      
      // Long to decimal conversion cannot overflow.
      decimalVal = System::Convert::ToDecimal( longVal );
      System::Console::WriteLine( " {0} as a decimal is {1}",
         longVal, decimalVal );
      
      // Decimal to long conversion can overflow.
      try
      {
         longVal = System::Convert::ToInt64( decimalVal );
         System::Console::WriteLine( " {0} as a long is {1}",
         decimalVal, longVal );
      }
      catch ( System::OverflowException^ ) 
      {
         System::Console::WriteLine( "Overflow in decimal-to-long conversion." );
      }
   }
public void ConvertLongDecimal(long longVal) {

    decimal	decimalVal;
    
    // Long to decimal conversion cannot overflow.
    decimalVal = System.Convert.ToDecimal(longVal);
    System.Console.WriteLine("{0} as a decimal is {1}",
            longVal, decimalVal);

    // Decimal to long conversion can overflow.
    try {
        longVal = System.Convert.ToInt64(decimalVal);
        System.Console.WriteLine("{0} as a long is {1}",
            decimalVal, longVal);
    }
    catch (System.OverflowException) {
        System.Console.WriteLine(
            "Overflow in decimal-to-long conversion.");
    }
}
let convertLongDecimal (longVal: int64) =
    // Long to decimal conversion cannot overflow.
    let decimalVal = Convert.ToDecimal longVal
    printfn $"{longVal} as a decimal is {decimalVal}"

    // Decimal to long conversion can overflow.
    try
        let longVal = Convert.ToInt64 decimalVal
        printfn $"{decimalVal} as a long is {longVal}"
    with :? OverflowException ->
        printfn "Overflow in decimal-to-long conversion."
Public Sub ConvertLongDecimal(ByVal longVal As Long)

    Dim decimalVal As Decimal

    'Long to Decimal conversion cannot overflow.
    decimalVal = System.Convert.ToDecimal(longVal)
    System.Console.WriteLine("{0} as a Decimal is {1}", _
                              longVal, decimalVal)

    'Decimal to Long conversion can overflow.
    Try
        longVal = System.Convert.ToInt64(decimalVal)
        System.Console.WriteLine("{0} as a Long is {1}", _
                                  decimalVal, longVal)
    Catch exception As System.OverflowException
        System.Console.WriteLine( _
            "Overflow in decimal-to-long conversion.")
    End Try
End Sub

См. также раздел

Применяется к

ToDecimal(Int32)

Исходный код:
Convert.cs
Исходный код:
Convert.cs
Исходный код:
Convert.cs

Преобразует значение заданного 32-разрядного знакового целого числа в эквивалентное десятичное число.

public:
 static System::Decimal ToDecimal(int value);
public static decimal ToDecimal (int value);
static member ToDecimal : int -> decimal
Public Shared Function ToDecimal (value As Integer) As Decimal

Параметры

value
Int32

32-разрядное целое число со знаком для преобразования.

Возвращаемое значение

Десятичное число, которое эквивалентно значению value.

Примеры

В следующем примере массив целых чисел со знаком преобразуется Decimal в значения.

int[] numbers = { Int32.MinValue, -1000, 0, 1000, Int32.MaxValue };
decimal result;

foreach (int number in numbers)
{
   result = Convert.ToDecimal(number);
   Console.WriteLine("Converted the Int32 value {0} to the Decimal value {1}.",
                     number, result);
}
// The example displays the following output:
//    Converted the Int32 value -2147483648 to the Decimal value -2147483648.
//    Converted the Int32 value -1000 to the Decimal value -1000.
//    Converted the Int32 value 0 to the Decimal value 0.
//    Converted the Int32 value 1000 to the Decimal value 1000.
//    Converted the Int32 value 2147483647 to the Decimal value 2147483647.
let numbers =
    [| Int32.MinValue; -1000; 0; 1000; Int32.MaxValue |]

for number in numbers do
    let result = Convert.ToDecimal number
    printfn $"Converted the Int32 value {number} to the Decimal value {result}."
// The example displays the following output:
//    Converted the Int32 value -2147483648 to the Decimal value -2147483648.
//    Converted the Int32 value -1000 to the Decimal value -1000.
//    Converted the Int32 value 0 to the Decimal value 0.
//    Converted the Int32 value 1000 to the Decimal value 1000.
//    Converted the Int32 value 2147483647 to the Decimal value 2147483647.
Dim numbers() As Integer = { Int32.MinValue, -1000, 0, 1000, Int32.MaxValue }
Dim result As Decimal

For Each number As Integer In numbers
   result = Convert.ToDecimal(number)
   Console.WriteLine("Converted the Int32 value {0} to the Decimal value {1}.", _
                     number, result)
Next
' The example displays the following output:
'    Converted the Int32 value -2147483648 to the Decimal value -2147483648.
'    Converted the Int32 value -1000 to the Decimal value -1000.
'    Converted the Int32 value 0 to the Decimal value 0.
'    Converted the Int32 value 1000 to the Decimal value 1000.
'    Converted the Int32 value 2147483647 to the Decimal value 2147483647.

См. также раздел

Применяется к

ToDecimal(Int16)

Исходный код:
Convert.cs
Исходный код:
Convert.cs
Исходный код:
Convert.cs

Преобразует значение заданного 16-разрядного знакового целого числа в эквивалентное десятичное число.

public:
 static System::Decimal ToDecimal(short value);
public static decimal ToDecimal (short value);
static member ToDecimal : int16 -> decimal
Public Shared Function ToDecimal (value As Short) As Decimal

Параметры

value
Int16

16-разрядное целое число со знаком для преобразования.

Возвращаемое значение

Десятичное число, которое эквивалентно значению value.

Примеры

В следующем примере массив 16-разрядных целых чисел со знаком преобразуется Decimal в значения.

short[] numbers = { Int16.MinValue, -1000, 0, 1000, Int16.MaxValue };
decimal result;

foreach (short number in numbers)
{
   result = Convert.ToDecimal(number);
   Console.WriteLine("Converted the Int16 value {0} to the Decimal value {1}.",
                     number, result);
}
// The example displays the following output:
//       Converted the Int16 value -32768 to the Decimal value -32768.
//       Converted the Int16 value -1000 to the Decimal value -1000.
//       Converted the Int16 value 0 to the Decimal value 0.
//       Converted the Int16 value 1000 to the Decimal value 1000.
//       Converted the Int16 value 32767 to the Decimal value 32767.
let numbers = 
    [| Int16.MinValue; -1000s; 0s; 1000s; Int16.MaxValue |]

for number in numbers do
    let result = Convert.ToDecimal number
    printfn $"Converted the Int16 value {number} to the Decimal value {result}."
// The example displays the following output:
//       Converted the Int16 value -32768 to the Decimal value -32768.
//       Converted the Int16 value -1000 to the Decimal value -1000.
//       Converted the Int16 value 0 to the Decimal value 0.
//       Converted the Int16 value 1000 to the Decimal value 1000.
//       Converted the Int16 value 32767 to the Decimal value 32767.
Dim numbers() As Short = { Int16.MinValue, -1000, 0, 1000, Int16.MaxValue }
Dim result As Decimal

For Each number As Short In numbers
   result = Convert.ToDecimal(number)
   Console.WriteLine("Converted the Int16 value {0} to the Decimal value {1}.", _
                     number, result)
Next
' The example displays the following output:
'       Converted the Int16 value -32768 to the Decimal value -32768.
'       Converted the Int16 value -1000 to the Decimal value -1000.
'       Converted the Int16 value 0 to the Decimal value 0.
'       Converted the Int16 value 1000 to the Decimal value 1000.
'       Converted the Int16 value 32767 to the Decimal value 32767.

См. также раздел

Применяется к

ToDecimal(Double)

Исходный код:
Convert.cs
Исходный код:
Convert.cs
Исходный код:
Convert.cs

Преобразует значение заданного числа с плавающей запятой двойной точности в эквивалентное десятичное число.

public:
 static System::Decimal ToDecimal(double value);
public static decimal ToDecimal (double value);
static member ToDecimal : double -> decimal
Public Shared Function ToDecimal (value As Double) As Decimal

Параметры

value
Double

Число с плавающей запятой двойной точности, которое нужно преобразовать.

Возвращаемое значение

Десятичное число, которое эквивалентно значению value.

Исключения

value Значение больше Decimal.MaxValue или меньше Decimal.MinValue.

Примеры

В следующем примере значение преобразуется Double в Decimal значение .

public:
   void ConvertDoubleDecimal( double doubleVal )
   {
      Decimal decimalVal;
      
      // Conversion from double to decimal cannot overflow.
      decimalVal = System::Convert::ToDecimal( doubleVal );
      System::Console::WriteLine( " {0} as a decimal is: {1}",
         doubleVal, decimalVal );
      
      // Decimal to double conversion can overflow.
      try
      {
         doubleVal = System::Convert::ToDouble( decimalVal );
         System::Console::WriteLine( " {0} as a double is: {1}",
         decimalVal, doubleVal );
      }
      catch ( System::OverflowException^ ) 
      {
         System::Console::WriteLine( "Overflow in decimal-to-double conversion." );
      }
   }
public void ConvertDoubleDecimal(decimal decimalVal){
    
    double doubleVal;
    
    // Decimal to double conversion cannot overflow.
 doubleVal = System.Convert.ToDouble(decimalVal);
    System.Console.WriteLine("{0} as a double is: {1}",
            decimalVal, doubleVal);

    // Conversion from double to decimal can overflow.
    try
 {
       decimalVal = System.Convert.ToDecimal(doubleVal);
    System.Console.WriteLine ("{0} as a decimal is: {1}",
        doubleVal, decimalVal);
    }
    catch (System.OverflowException) {
        System.Console.WriteLine(
            "Overflow in double-to-double conversion.");
    }
}
let convertDoubleDecimal (decimalVal: float) =
    // Decimal to double conversion cannot overflow.
    let doubleVal = 
        Convert.ToDouble decimalVal
    printfn $"{decimalVal} as a double is: {doubleVal}"

    // Conversion from double to decimal can overflow.
    try
        let decimalVal = Convert.ToDecimal doubleVal
        printfn $"{doubleVal} as a decimal is: {decimalVal}"
    with :? OverflowException ->
        printfn "Overflow in double-to-double conversion."
Public Sub ConvertDoubleDecimal(ByVal decimalVal As Decimal)

    Dim doubleVal As Double

    ' Decimal to Double conversion cannot overflow.
    doubleVal = System.Convert.ToDouble(decimalVal)
    System.Console.WriteLine("{0} as a Double is: {1}", _
                             decimalVal, doubleVal)
    
    ' Conversion from Double to Decimal can overflow.
    Try
       decimalVal = System.Convert.ToDecimal(doubleVal)
       System.Console.WriteLine("{0} as a Decimal is: {1}", _
                                doubleVal, decimalVal)
    Catch exception As System.OverflowException
        System.Console.WriteLine( _
            "Overflow in Double-to-Decimal conversion.")
    End Try

End Sub

Комментарии

Значение Decimal , возвращаемое этим методом, содержит не более 15 значимых цифр. value Если параметр содержит более 15 значимых цифр, он округляется с помощью округления до ближайшего. В следующем примере показано, как Convert.ToDecimal(Double) метод использует округление до ближайшего Decimal для возврата значения с 15 значащими цифрами.

Console.WriteLine(Convert.ToDecimal(123456789012345500.12D));  // Displays 123456789012346000
Console.WriteLine(Convert.ToDecimal(123456789012346500.12D));  // Displays 123456789012346000

Console.WriteLine(Convert.ToDecimal(10030.12345678905D));      // Displays 10030.123456789
Console.WriteLine(Convert.ToDecimal(10030.12345678915D));      // Displays 10030.1234567892
printfn $"{Convert.ToDecimal 123456789012345500.12}"  // Displays 123456789012346000
printfn $"{Convert.ToDecimal 123456789012346500.12}"  // Displays 123456789012346000

printfn $"{Convert.ToDecimal 10030.12345678905}"      // Displays 10030.123456789
printfn $"{Convert.ToDecimal 10030.12345678915}"      // Displays 10030.1234567892
Console.WriteLine(Convert.ToDecimal(123456789012345500.12R))   ' Displays 123456789012346000
Console.WriteLine(Convert.ToDecimal(123456789012346500.12R))   ' Displays 123456789012346000

Console.WriteLine(Convert.ToDecimal(10030.12345678905R))       ' Displays 10030.123456789 
Console.WriteLine(Convert.ToDecimal(10030.12345678915R))       ' Displays 10030.1234567892

См. также раздел

Применяется к

ToDecimal(Decimal)

Исходный код:
Convert.cs
Исходный код:
Convert.cs
Исходный код:
Convert.cs

Возвращает заданное десятичное число; фактическое преобразование не производится.

public:
 static System::Decimal ToDecimal(System::Decimal value);
public static decimal ToDecimal (decimal value);
static member ToDecimal : decimal -> decimal
Public Shared Function ToDecimal (value As Decimal) As Decimal

Параметры

value
Decimal

Десятичное число.

Возвращаемое значение

value возвращается без изменений.

Применяется к

ToDecimal(DateTime)

Исходный код:
Convert.cs
Исходный код:
Convert.cs
Исходный код:
Convert.cs

При вызове этого метода всегда возникает исключение InvalidCastException.

public:
 static System::Decimal ToDecimal(DateTime value);
public static decimal ToDecimal (DateTime value);
static member ToDecimal : DateTime -> decimal
Public Shared Function ToDecimal (value As DateTime) As Decimal

Параметры

value
DateTime

Значение даты и времени для преобразования.

Возвращаемое значение

Это преобразование не поддерживается. Возвращаемое значение отсутствует.

Исключения

Это преобразование не поддерживается.

Применяется к

ToDecimal(Char)

Исходный код:
Convert.cs
Исходный код:
Convert.cs
Исходный код:
Convert.cs

При вызове этого метода всегда возникает исключение InvalidCastException.

public:
 static System::Decimal ToDecimal(char value);
public static decimal ToDecimal (char value);
static member ToDecimal : char -> decimal
Public Shared Function ToDecimal (value As Char) As Decimal

Параметры

value
Char

Знак Юникода, который необходимо преобразовать.

Возвращаемое значение

Это преобразование не поддерживается. Возвращаемое значение отсутствует.

Исключения

Это преобразование не поддерживается.

Примеры

В следующем примере показано, как преобразовать значение в CharDecimal, и возникает InvalidCastException исключение при сбое.

public:
   void ConvertCharDecimal( Char charVal )
   {
      Decimal decimalVal = 0;
      
      // Char to decimal conversion is not supported and will always
      // throw an InvalidCastException.
      try
      {
         decimalVal = System::Convert::ToDecimal( charVal );
      }
      catch ( System::InvalidCastException^ ) 
      {
         System::Console::WriteLine(
            "Char-to-Decimal conversion is not supported by the .NET Framework." );
      }
      
      //Decimal to char conversion is also not supported.
      try
      {
         charVal = System::Convert::ToChar( decimalVal );
      }
      catch ( System::InvalidCastException^ ) 
      {
         System::Console::WriteLine(
            "Decimal-to-Char conversion is not supported by the .NET Framework." );
      }
   }
public void ConvertCharDecimal(char charVal) {
    Decimal decimalVal = 0;
    
    // Char to decimal conversion is not supported and will always
    // throw an InvalidCastException.
    try {
        decimalVal = System.Convert.ToDecimal(charVal);
    }
    catch (System.InvalidCastException) {
        System.Console.WriteLine(
            "Char-to-Decimal conversion is not supported " +
            "by the .NET Framework.");
    }

    //Decimal to char conversion is also not supported.
    try {
        charVal = System.Convert.ToChar(decimalVal);
    }
    catch (System.InvalidCastException) {
        System.Console.WriteLine(
            "Decimal-to-Char conversion is not supported " +
            "by the .NET Framework.");
    }
}
let convertCharDecimal (charVal: char) =
    let decimalVal = 0m

    // Char to decimal conversion is not supported and will always
    // throw an InvalidCastException.
    try
        let decimalVal = Convert.ToDecimal charVal
        ()
    with :? InvalidCastException ->
        printfn "Char-to-Decimal conversion is not supported by the .NET Runtime."

    //Decimal to char conversion is also not supported.
    try
        let charVal = Convert.ToChar decimalVal
        ()
    with :? InvalidCastException ->
        printfn "Decimal-to-Char conversion is not supported by the .NET Runtime."
Public Sub ConvertCharDecimal(ByVal charVal As Char)
    Dim decimalVal As [Decimal] = 0

    ' Char to decimal conversion is not supported and will always
    ' throw an InvalidCastException.
    Try
        decimalVal = System.Convert.ToDecimal(charVal)
    Catch exception As System.InvalidCastException
        System.Console.WriteLine( _
             "Char-to-Decimal conversion is not supported " + _
             "by the .NET Framework.")
    End Try

    'Decimal to char conversion is also not supported.
    Try
        charVal = System.Convert.ToChar(decimalVal)
    Catch exception As System.InvalidCastException
        System.Console.WriteLine( _
            "Decimal-to-Char conversion is not supported " + _
            "by the .NET Framework.")
    End Try
End Sub

См. также раздел

Применяется к

ToDecimal(Byte)

Исходный код:
Convert.cs
Исходный код:
Convert.cs
Исходный код:
Convert.cs

Преобразует значение заданного 8-разрядного целого число без знака в эквивалентное десятичное число.

public:
 static System::Decimal ToDecimal(System::Byte value);
public static decimal ToDecimal (byte value);
static member ToDecimal : byte -> decimal
Public Shared Function ToDecimal (value As Byte) As Decimal

Параметры

value
Byte

8-разрядное целое число без знака для преобразования.

Возвращаемое значение

Десятичное число, которое эквивалентно значению value.

Примеры

В следующем примере значение преобразуется Byte в Decimal значение .

public:
   void ConvertByteDecimal( Byte byteVal )
   {
      Decimal decimalVal;
      
      // Byte to decimal conversion will not overflow.
      decimalVal = System::Convert::ToDecimal( byteVal );
      System::Console::WriteLine( "The Byte as a decimal is {0}.",
         decimalVal );
      
      // Decimal to Byte conversion can overflow.
      try
      {
         byteVal = System::Convert::ToByte( decimalVal );
         System::Console::WriteLine( "The Decimal as a Byte is {0}.",
         byteVal );
      }
      catch ( System::OverflowException^ ) 
      {
         System::Console::WriteLine(
            "The decimal value is too large for a Byte." );
      }
   }
public void ConvertByteDecimal(byte byteVal) {
    decimal decimalVal;

    // Byte to decimal conversion will not overflow.
    decimalVal = System.Convert.ToDecimal(byteVal);
    System.Console.WriteLine("The byte as a decimal is {0}.",
        decimalVal);

    // Decimal to byte conversion can overflow.
    try {
        byteVal = System.Convert.ToByte(decimalVal);
        System.Console.WriteLine("The Decimal as a byte is {0}.",
            byteVal);
    }
    catch (System.OverflowException) {
        System.Console.WriteLine(
            "The decimal value is too large for a byte.");
    }
}
let convertByteDecimal (byteVal: byte) =
    // Byte to decimal conversion will not overflow.
    let decimalVal = Convert.ToDecimal byteVal
    printfn $"The byte as a decimal is {decimalVal}."

    // Decimal to byte conversion can overflow.
    try
        let byteVal = Convert.ToByte decimalVal
        printfn $"The Decimal as a byte is {byteVal}."
    with :? OverflowException ->
        printfn "The decimal value is too large for a byte."
Public Sub ConvertByteDecimal(ByVal byteVal As Byte)
    Dim decimalVal As Decimal

    ' Byte to decimal conversion will not overflow.
    decimalVal = System.Convert.ToDecimal(byteVal)
    System.Console.WriteLine("The byte as a decimal is {0}.", _
                              decimalVal)

    ' Decimal to byte conversion can overflow.
    Try
        byteVal = System.Convert.ToByte(decimalVal)
        System.Console.WriteLine("The Decimal as a byte is {0}.", _
                                  byteVal)
    Catch exception As System.OverflowException
        System.Console.WriteLine( _
            "Overflow in decimal-to-byte conversion.")
    End Try
End Sub

См. также раздел

Применяется к

ToDecimal(Boolean)

Исходный код:
Convert.cs
Исходный код:
Convert.cs
Исходный код:
Convert.cs

Преобразует заданное логическое значение в эквивалентное десятичное число.

public:
 static System::Decimal ToDecimal(bool value);
public static decimal ToDecimal (bool value);
static member ToDecimal : bool -> decimal
Public Shared Function ToDecimal (value As Boolean) As Decimal

Параметры

value
Boolean

Логическое значение, которое необходимо преобразовать.

Возвращаемое значение

Число 1, если value имеет значение true; в противном случае — 0.

Примеры

В следующем примере показано преобразование в BooleanDecimal значения.

bool[] flags = { true, false };
decimal result;

foreach (bool flag in flags)
{
   result = Convert.ToDecimal(flag);
   Console.WriteLine("Converted {0} to {1}.", flag, result);
}
// The example displays the following output:
//       Converted True to 1.
//       Converted False to 0.
let flags = [ true; false ]

for flag in flags do
    let result = Convert.ToDecimal flag
    printfn $"Converted {flag} to {result}."
// The example displays the following output:
//       Converted True to 1.
//       Converted False to 0.
Dim flags() As Boolean = { True, False }
Dim result As Decimal

For Each flag As Boolean In flags
   result = Convert.ToDecimal(flag)
   Console.WriteLine("Converted {0} to {1}.", flag, result)
Next
' The example displays the following output:
'       Converted True to 1.
'       Converted False to 0.

См. также раздел

Применяется к