0

I´m using some textboxes to show totals, subtotals and discounts. I´m converting decimals to string to represent them in the textbox. Also, I would like to have the "$" at the beginning.

I have achieved this by using this:

tbx_total.Text = total.ToString("$ ##0.##");

Graphically, this is working great, but my big problem is that I need that textbox value to calculate other ones. Basically, I get a formatting error during runtime when I try to convert that textbox text to decimal. Obviously, this is due to the ToString("$ ##0.##") format. Is there any way to get the value without the format?

2
  • 1
    Store your value in your object then represent its value what you want and where you want. Commented Jan 9, 2013 at 15:18
  • Yes, I know, but I create the textboxes in runtime. I add every created textbox in a list and then I use the list when I need to sum. Thats why I didnt consider it a choice.
    – Andres
    Commented Jan 9, 2013 at 15:48

4 Answers 4

2

One simple solution will be:

tbx_total.Text = total.ToString("$ ##0.##");
tbx_total.Tag = total;

Then use tbx_total.Tag property for further usage.

1
  • I´m disappointed with not been able to get the unformatted text without doing a tedious work. Anyways, I think your solution is the one that suits me better. Thanks for your answer and time.
    – Andres
    Commented Jan 9, 2013 at 16:46
1

When reading it back in you can parse with NumberStyles to get your desired effect. There is a number of bit-wise operations on NumberStyles so I suggest researching how to use them for more flexibility:

double.Parse(total, NumberStyles.Currency);

Also I tend to like this for formatting currency a bit more but purely stylistic.

String.Format("{0:C}", total);

Note: Parsing back and forth does incur some overhead so depending on the amount of data it may be more wise to offload the value to an object and reference that when you need the decimal value again.

1

As an alternative, you can do this, whenever you read the value:

double value = 0;
if (!double.TryParse(tbx_total.Text.TrimStart(new char[] { '$', ' ' }), out value))
{
      //Ooops... not a valid number
}

So here you basically remove the added '$' and space before the number enabling you to parse it as a double. This way you can check if the number has been entered correctly (provided that the user can edit the textbox.

0

I think you should store your original values (decimal) in a DataTable or some other collection and use these values to calculate what you need.

So you can format decimal values in any format you like without warry about how to convert back from strings.

Not the answer you're looking for? Browse other questions tagged or ask your own question.