C# Decimal Parse(String)

Description

Decimal Parse(String) converts the string representation of a number to its Decimal equivalent.

Syntax

Decimal.Parse(String) has the following syntax.


public static decimal Parse(
  string s
)

Parameters

Decimal.Parse(String) has the following parameters.

  • s - The string representation of the number to convert.

Returns

Decimal.Parse(String) method returns The equivalent to the number contained in s.

Example

The following code example uses the Parse(String) method to parse string representations of Decimal values.


using System;/*  w w  w . j  av a 2  s .  c o m*/
public class MainClass{
  public static void Main(String[] argv){  
    string value;
    decimal number;

    value = "16,523,421";
    number = Decimal.Parse(value);
    System.Console.WriteLine("'{0}' converted to {1}.", value, number);

    value = "25,162.1378";
    number = Decimal.Parse(value);
    System.Console.WriteLine("'{0}' converted to {1}.", value, number);

   
    value = "$16,321,421.75";
    number = Decimal.Parse(value);
    System.Console.WriteLine("'{0}' converted to {1}.", value, number);
   
    value = "1.62345e-02";
    number = Decimal.Parse(value);
    System.Console.WriteLine("'{0}' converted to {1}.", value, number);    
  }
}
    

The code above generates the following result.

Example 2

Parse string using "$" as the currency symbol for en-GB and en-us cultures.


using System;//  ww  w .j a  v a  2s  .  c om
using System.Globalization;
class MainClass
{
    public static void Main()
    {
        string value = "$6,543.21";
        NumberStyles style = NumberStyles.Number | NumberStyles.AllowCurrencySymbol;
        CultureInfo provider = new CultureInfo("en-GB");

        try
        {
            decimal number = Decimal.Parse(value, style, provider);
            Console.WriteLine("'{0}' converted to {1}.", value, number);
        }
        catch (FormatException)
        {
            Console.WriteLine("Unable to parse '{0}'.", value);
        }
    }
}

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