[C# Helper]
Index Books FAQ Contact About Rod
[Beginning Database Design Solutions, Second Edition]

[Beginning Software Engineering, Second Edition]

[Essential Algorithms, Second Edition]

[The Modern C# Challenge]

[WPF 3d, Three-Dimensional Graphics with WPF and C#]

[The C# Helper Top 100]

[Interview Puzzles Dissected]

[C# 24-Hour Trainer]

[C# 5.0 Programmer's Reference]

[MCSD Certification Toolkit (Exam 70-483): Programming in C#]

Title: 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 the example to experiment with it and to see additional details.

© 2009-2023 Rocky Mountain Computer Consulting, Inc. All rights reserved.