C# Convert ToDecimal(String, IFormatProvider)

Description

Convert ToDecimal(String, IFormatProvider) converts the specified string representation of a number to an equivalent decimal number, using the specified culture-specific formatting information.

Syntax

Convert.ToDecimal(String, IFormatProvider) has the following syntax.


public static decimal ToDecimal(
  string value,
  IFormatProvider provider
)

Parameters

Convert.ToDecimal(String, IFormatProvider) has the following parameters.

  • value - A string that contains a number to convert.
  • provider - An object that supplies culture-specific formatting information.

Returns

Convert.ToDecimal(String, IFormatProvider) method returns A decimal number that is equivalent to the number in value, or 0 (zero) if value is null.

Example

The following example attempts to convert an array of strings to Decimal values by using NumberFormatInfo objects that represent two different cultures.


using System;/*from w  w w  .j  a  va2s. co  m*/
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 code above generates the following result.





















Home »
  C# Tutorial »
    System »




Array
BitConverter
Boolean
Byte
Char
Console
ConsoleKeyInfo
Convert
DateTime
DateTimeOffset
Decimal
Double
Enum
Environment
Exception
Guid
Int16
Int32
Int64
Math
OperatingSystem
Random
SByte
Single
String
StringComparer
TimeSpan
TimeZone
TimeZoneInfo
Tuple
Tuple
Tuple
Type
UInt16
UInt32
UInt64
Uri
Version