Parse currency values in C#

parse currency values

Converting a decimal value into a currency formatted string is easy. Simply use its ToString method, passing it the parameter “C” as in the following code.

txtAny.Text = value.ToString("C");

Strangely parsing a currency value entered by the user is not as simple. By default, decimal.Parse doesn’t understand currency symbols or parentheses used to indicate negative values.

The solution is to pass decimal.Parse as a second parameter the value NumberStyles.Any, which is defined in the System.Globalization namespace. The following code correctly parses currency values.

decimal value = decimal.Parse(txtValue.Text, NumberStyles.Any);

This example uses the following code to parse values entered by the user.

// Parse the entered value.
private void btnParse_Click(object sender, EventArgs e)
{
    // Default parsing behavior.
    try
    {
        decimal value = decimal.Parse(txtValue.Text);
        txtDefault.Text = value.ToString("C");
    }
    catch (Exception ex)
    {
        txtDefault.Text = ex.Message;
    }

    // Parse with Any format.
    try
    {
        decimal value = decimal.Parse(txtValue.Text,
            NumberStyles.Any);
        txtAny.Text = value.ToString("C");
    }
    catch (Exception ex)
    {
        txtAny.Text = ex.Message;
    }
}

First the code tries to parse the value normally. It then tries to parse it while using the NumberStyles.Any parameter. If it encounters an exception, the program displays the exception message. Otherwise it displays the value it parsed.


Download Example   Follow me on Twitter   RSS feed


This entry was posted in parsing, syntax and tagged , , , , , , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *