Ler em inglês

Compartilhar via


Convert.ToDecimal Método

Definição

Converte um valor especificado em um número decimal.

Sobrecargas

ToDecimal(Single)

Converte o valor do número de ponto flutuante de precisão simples para um número decimal equivalente.

ToDecimal(String)

Converte a representação de cadeia de caracteres especificada de um número para um número decimal equivalente.

ToDecimal(UInt16)

Converte o valor do inteiro sem sinal de 16 bits especificado em um número decimal equivalente.

ToDecimal(String, IFormatProvider)

Converte a representação de cadeia de caracteres especificada de um número em um número decimal equivalente, usando as informações de formatação específicas da cultura especificada.

ToDecimal(UInt64)

Converte o valor do inteiro sem sinal de 64 bits especificado em um número decimal equivalente.

ToDecimal(Object, IFormatProvider)

Converte o valor do objeto especificado em um número decimal equivalente, usando as informações de formatação específicas da cultura especificada.

ToDecimal(SByte)

Converte o valor do inteiro com sinal de 8 bits especificado no número decimal equivalente.

ToDecimal(UInt32)

Converte o valor do inteiro sem sinal de 32 bits especificado em um número decimal equivalente.

ToDecimal(Object)

Converte o valor do objeto especificado em um número decimal equivalente.

ToDecimal(Int64)

Converte o valor do inteiro com sinal de 64 bits especificado em um número decimal equivalente.

ToDecimal(Int32)

Converte o valor do inteiro com sinal de 32 bits especificado em um número decimal equivalente.

ToDecimal(Int16)

Converte o valor do inteiro com sinal de 16 bits especificado em um número decimal equivalente.

ToDecimal(Double)

Converte o valor do número de ponto flutuante de dupla precisão para um número decimal equivalente.

ToDecimal(Decimal)

Retorna o número decimal especificado; nenhuma conversão real é executada.

ToDecimal(DateTime)

A chamada desse método sempre lança InvalidCastException.

ToDecimal(Char)

A chamada desse método sempre lança InvalidCastException.

ToDecimal(Byte)

Converte o valor do inteiro sem sinal de 8 bits especificado no número decimal equivalente.

ToDecimal(Boolean)

Converte o valor booliano especificado para o número decimal equivalente.

ToDecimal(Single)

Origem:
Convert.cs
Origem:
Convert.cs
Origem:
Convert.cs

Converte o valor do número de ponto flutuante de precisão simples para um número decimal equivalente.

C#
public static decimal ToDecimal (float value);

Parâmetros

value
Single

O número de ponto flutuante de precisão simples a ser convertido.

Retornos

Um número decimal equivalente a value.

Exceções

value é maior que Decimal.MaxValue ou menor que Decimal.MinValue.

Exemplos

O exemplo a seguir tenta converter cada elemento em uma matriz de Single valores em um Decimal valor .

C#
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.

Comentários

O Decimal valor retornado por esse método contém um máximo de sete dígitos significativos. Se o value parâmetro contiver mais de sete dígitos significativos, ele será arredondado usando o arredondamento para o mais próximo. O exemplo a seguir ilustra como o método usa arredondamento ToDecimal(Single) para mais próximo para retornar um Decimal valor com sete dígitos significativos.

C#
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

Confira também

Aplica-se a

.NET 9 e outras versões
Produto Versões
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0

ToDecimal(String)

Origem:
Convert.cs
Origem:
Convert.cs
Origem:
Convert.cs

Converte a representação de cadeia de caracteres especificada de um número para um número decimal equivalente.

C#
public static decimal ToDecimal (string value);
C#
public static decimal ToDecimal (string? value);

Parâmetros

value
String

Uma cadeia de caracteres que contém um número a ser convertido.

Retornos

Um número decimal equivalente ao número em value, ou 0 (zero), se value for null.

Exceções

value não é um número em um formato válido.

value representa um número menor que Decimal.MinValue ou maior que Decimal.MaxValue.

Exemplos

O exemplo a seguir ilustra o uso de ToDecimal. Ele tenta converter um String em um Decimale gera as possíveis exceções que podem surgir durante a conversão.

C#
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);
}

Comentários

Usar o ToDecimal(String) método é equivalente a passar value para o Decimal.Parse(String) método . value é interpretado usando as convenções de formatação da cultura atual.

Se preferir não manipular uma exceção se a conversão falhar, você poderá chamar o Decimal.TryParse método em vez disso. Ele retorna um valor Boolean que indica se a conversão foi bem-sucedida ou falhou.

Aplica-se a

.NET 9 e outras versões
Produto Versões
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0

ToDecimal(UInt16)

Origem:
Convert.cs
Origem:
Convert.cs
Origem:
Convert.cs

Importante

Esta API não está em conformidade com CLS.

Converte o valor do inteiro sem sinal de 16 bits especificado em um número decimal equivalente.

C#
[System.CLSCompliant(false)]
public static decimal ToDecimal (ushort value);

Parâmetros

value
UInt16

O inteiro não assinado de 16 bits a ser convertido.

Retornos

O número decimal equivalente a value.

Atributos

Exemplos

O exemplo a seguir converte uma matriz de inteiros sem sinal de 16 bits Decimal em valores.

C#
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.

Confira também

Aplica-se a

.NET 9 e outras versões
Produto Versões
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0

ToDecimal(String, IFormatProvider)

Origem:
Convert.cs
Origem:
Convert.cs
Origem:
Convert.cs

Converte a representação de cadeia de caracteres especificada de um número em um número decimal equivalente, usando as informações de formatação específicas da cultura especificada.

C#
public static decimal ToDecimal (string value, IFormatProvider provider);
C#
public static decimal ToDecimal (string? value, IFormatProvider? provider);

Parâmetros

value
String

Uma cadeia de caracteres que contém um número a ser convertido.

provider
IFormatProvider

Um objeto que fornece informações de formatação específicas da cultura.

Retornos

Um número decimal equivalente ao número em value, ou 0 (zero), se value for null.

Exceções

value não é um número em um formato válido.

value representa um número menor que Decimal.MinValue ou maior que Decimal.MaxValue.

Exemplos

O exemplo a seguir tenta converter uma matriz de cadeias de caracteres em Decimal valores usando NumberFormatInfo objetos que representam duas culturas diferentes.

C#
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

Comentários

O valor retornado é o resultado da invocação do Decimal.Parse método em value.

provider é uma IFormatProvider instância que obtém um NumberFormatInfo objeto . O objeto NumberFormatInfo fornece informações específicas da cultura sobre o formato de value. Caso provider seja null, NumberFormatInfo da cultura atual é usado.

Se preferir não manipular uma exceção se a conversão falhar, você poderá chamar o Decimal.TryParse método em vez disso. Ele retorna um valor Boolean que indica se a conversão foi bem-sucedida ou falhou.

Aplica-se a

.NET 9 e outras versões
Produto Versões
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0

ToDecimal(UInt64)

Origem:
Convert.cs
Origem:
Convert.cs
Origem:
Convert.cs

Importante

Esta API não está em conformidade com CLS.

Converte o valor do inteiro sem sinal de 64 bits especificado em um número decimal equivalente.

C#
[System.CLSCompliant(false)]
public static decimal ToDecimal (ulong value);

Parâmetros

value
UInt64

O inteiro sem sinal de 64 bits a ser convertido.

Retornos

Um número decimal equivalente a value.

Atributos

Exemplos

O exemplo a seguir converte uma matriz de inteiros longos Decimal sem sinal em valores.

C#
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.

Confira também

Aplica-se a

.NET 9 e outras versões
Produto Versões
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0

ToDecimal(Object, IFormatProvider)

Origem:
Convert.cs
Origem:
Convert.cs
Origem:
Convert.cs

Converte o valor do objeto especificado em um número decimal equivalente, usando as informações de formatação específicas da cultura especificada.

C#
public static decimal ToDecimal (object value, IFormatProvider provider);
C#
public static decimal ToDecimal (object? value, IFormatProvider? provider);

Parâmetros

value
Object

Um objeto que implementa a interface do IConvertible.

provider
IFormatProvider

Um objeto que fornece informações de formatação específicas da cultura.

Retornos

Um número decimal equivalente a value ou 0 (zero) se value for null.

Exceções

value não está em um formato apropriado para um tipo Decimal.

value não implementa a interface IConvertible.

- ou -

A conversão não é suportada.

value representa um número menor que Decimal.MinValue ou maior que Decimal.MaxValue.

Exemplos

O exemplo a seguir define uma classe Temperature que implementa a interface IConvertible.

C#
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);
   }
}

O exemplo a Temperature seguir mostra que quando um Temperature objeto é passado como um parâmetro para o ToDecimal(Object, IFormatProvider) método , a IConvertible.ToDecimal implementação da classe é chamada para executar a conversão.

C#
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

Comentários

O valor retornado é o resultado da invocação do IConvertible.ToDecimal método do tipo subjacente de value.

provider permite que o usuário especifique informações de conversão específicas da cultura sobre o conteúdo de value. Os tipos de base ignoram provider; no entanto, o parâmetro pode ser usado caso value seja um tipo definido pelo usuário que implementa a interface IConvertible.

Confira também

Aplica-se a

.NET 9 e outras versões
Produto Versões
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0

ToDecimal(SByte)

Origem:
Convert.cs
Origem:
Convert.cs
Origem:
Convert.cs

Importante

Esta API não está em conformidade com CLS.

Converte o valor do inteiro com sinal de 8 bits especificado no número decimal equivalente.

C#
[System.CLSCompliant(false)]
public static decimal ToDecimal (sbyte value);

Parâmetros

value
SByte

O inteiro com sinal de 8 bits a ser convertido.

Retornos

Um número decimal equivalente a value.

Atributos

Exemplos

O exemplo a seguir converte cada elemento em uma matriz de bytes assinados em um Decimal valor .

C#
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.

Confira também

Aplica-se a

.NET 9 e outras versões
Produto Versões
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0

ToDecimal(UInt32)

Origem:
Convert.cs
Origem:
Convert.cs
Origem:
Convert.cs

Importante

Esta API não está em conformidade com CLS.

Converte o valor do inteiro sem sinal de 32 bits especificado em um número decimal equivalente.

C#
[System.CLSCompliant(false)]
public static decimal ToDecimal (uint value);

Parâmetros

value
UInt32

O inteiro sem sinal de 32 bits a ser convertido.

Retornos

Um número decimal equivalente a value.

Atributos

Exemplos

O exemplo a seguir converte uma matriz de inteiros Decimal sem sinal em valores.

C#
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.

Confira também

Aplica-se a

.NET 9 e outras versões
Produto Versões
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0

ToDecimal(Object)

Origem:
Convert.cs
Origem:
Convert.cs
Origem:
Convert.cs

Converte o valor do objeto especificado em um número decimal equivalente.

C#
public static decimal ToDecimal (object value);
C#
public static decimal ToDecimal (object? value);

Parâmetros

value
Object

Um objeto que implementa a interface IConvertible ou null.

Retornos

Um número decimal equivalente a value ou 0 (zero) se value for null.

Exceções

value não está em um formato apropriado para um tipo Decimal.

value não implementa a interface IConvertible.

- ou -

A conversão não é suportada.

value representa um número menor que Decimal.MinValue ou maior que Decimal.MaxValue.

Exemplos

O exemplo a seguir tenta converter cada elemento em uma matriz de objetos em um Decimal valor .

C#
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.

Comentários

O valor retornado é o resultado da invocação do IConvertible.ToDecimal método do tipo subjacente de value.

Confira também

Aplica-se a

.NET 9 e outras versões
Produto Versões
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0

ToDecimal(Int64)

Origem:
Convert.cs
Origem:
Convert.cs
Origem:
Convert.cs

Converte o valor do inteiro com sinal de 64 bits especificado em um número decimal equivalente.

C#
public static decimal ToDecimal (long value);

Parâmetros

value
Int64

O inteiro com sinal de 64 bits a ser convertido.

Retornos

Um número decimal equivalente a value.

Exemplos

O exemplo a seguir converte um Int64 valor em um Decimal valor .

C#
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.");
    }
}

Confira também

Aplica-se a

.NET 9 e outras versões
Produto Versões
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0

ToDecimal(Int32)

Origem:
Convert.cs
Origem:
Convert.cs
Origem:
Convert.cs

Converte o valor do inteiro com sinal de 32 bits especificado em um número decimal equivalente.

C#
public static decimal ToDecimal (int value);

Parâmetros

value
Int32

O inteiro com sinal de 32 bits a converter.

Retornos

Um número decimal equivalente a value.

Exemplos

O exemplo a seguir converte uma matriz de inteiros Decimal com sinal em valores.

C#
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.

Confira também

Aplica-se a

.NET 9 e outras versões
Produto Versões
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0

ToDecimal(Int16)

Origem:
Convert.cs
Origem:
Convert.cs
Origem:
Convert.cs

Converte o valor do inteiro com sinal de 16 bits especificado em um número decimal equivalente.

C#
public static decimal ToDecimal (short value);

Parâmetros

value
Int16

O inteiro assinado de 16 bits a ser convertido.

Retornos

Um número decimal equivalente a value.

Exemplos

O exemplo a seguir converte uma matriz de inteiros com sinal de 16 bits Decimal em valores.

C#
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.

Confira também

Aplica-se a

.NET 9 e outras versões
Produto Versões
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0

ToDecimal(Double)

Origem:
Convert.cs
Origem:
Convert.cs
Origem:
Convert.cs

Converte o valor do número de ponto flutuante de dupla precisão para um número decimal equivalente.

C#
public static decimal ToDecimal (double value);

Parâmetros

value
Double

O número de ponto flutuante de precisão dupla a ser convertido.

Retornos

Um número decimal equivalente a value.

Exceções

value é maior que Decimal.MaxValue ou menor que Decimal.MinValue.

Exemplos

O exemplo a seguir converte um Double valor em um Decimal valor .

C#
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.");
    }
}

Comentários

O Decimal valor retornado por esse método contém um máximo de 15 dígitos significativos. Se o value parâmetro contiver mais de 15 dígitos significativos, ele será arredondado usando o arredondamento para o mais próximo. O exemplo a seguir ilustra como o método usa arredondamento Convert.ToDecimal(Double) para mais próximo para retornar um Decimal valor com 15 dígitos significativos.

C#
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

Confira também

Aplica-se a

.NET 9 e outras versões
Produto Versões
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0

ToDecimal(Decimal)

Origem:
Convert.cs
Origem:
Convert.cs
Origem:
Convert.cs

Retorna o número decimal especificado; nenhuma conversão real é executada.

C#
public static decimal ToDecimal (decimal value);

Parâmetros

value
Decimal

Um número decimal.

Retornos

value é retornado inalterado.

Aplica-se a

.NET 9 e outras versões
Produto Versões
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0

ToDecimal(DateTime)

Origem:
Convert.cs
Origem:
Convert.cs
Origem:
Convert.cs

A chamada desse método sempre lança InvalidCastException.

C#
public static decimal ToDecimal (DateTime value);

Parâmetros

value
DateTime

O valor de data e tempo a ser convertido.

Retornos

Não há suporte para esta conversão. Nenhum valor é retornado.

Exceções

Não há suporte para esta conversão.

Aplica-se a

.NET 9 e outras versões
Produto Versões
.NET Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 2.0, 2.1

ToDecimal(Char)

Origem:
Convert.cs
Origem:
Convert.cs
Origem:
Convert.cs

A chamada desse método sempre lança InvalidCastException.

C#
public static decimal ToDecimal (char value);

Parâmetros

value
Char

O caractere Unicode a ser convertido.

Retornos

Não há suporte para esta conversão. Nenhum valor é retornado.

Exceções

Não há suporte para esta conversão.

Exemplos

O exemplo a seguir tenta converter um Char valor em Decimale lança InvalidCastException em caso de falha.

C#
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.");
    }
}

Confira também

Aplica-se a

.NET 9 e outras versões
Produto Versões
.NET Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 2.0, 2.1

ToDecimal(Byte)

Origem:
Convert.cs
Origem:
Convert.cs
Origem:
Convert.cs

Converte o valor do inteiro sem sinal de 8 bits especificado no número decimal equivalente.

C#
public static decimal ToDecimal (byte value);

Parâmetros

value
Byte

O inteiro sem sinal de 8 bits a ser convertido.

Retornos

O número decimal equivalente a value.

Exemplos

O exemplo a seguir converte um Byte valor em um Decimal valor .

C#
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.");
    }
}

Confira também

Aplica-se a

.NET 9 e outras versões
Produto Versões
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0

ToDecimal(Boolean)

Origem:
Convert.cs
Origem:
Convert.cs
Origem:
Convert.cs

Converte o valor booliano especificado para o número decimal equivalente.

C#
public static decimal ToDecimal (bool value);

Parâmetros

value
Boolean

O valor booliano a ser convertido.

Retornos

O número 1 caso value seja true; do contrário, 0.

Exemplos

O exemplo a seguir ilustra a conversão de Boolean em Decimal valores .

C#
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.

Confira também

Aplica-se a

.NET 9 e outras versões
Produto Versões
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0