2

How do I convert a string that's a formatted number, back to a number?

  Decimal percent = 55.76;
  String strPercent = String.Format("{0:0.0}%", percent);
  Decimal dollars = 33.5;
  String strDollars = String.Format("{0:C}", dollars);

Say later, I want to get the percent and dollar value back, as numbers. Is there any built-in way to do this using C# and asp.net? I know how I use regex and a String function, but I read about a Decimal.Parse() function from http://msdn.microsoft.com/en-us/library/ks098hd7(vs.71).aspx.

Is there a built-in function to do this? If yes, how can I use it?

Lifes
  • 1,226
  • 2
  • 25
  • 45

2 Answers2

5

int.Parse, double.Parse, etc are your friends.

Edit: Missed the punctuation part. Will reinvestigate and come up with something better.

Edit 2: It turns out int.Parse actually has an overload to take the format string: http://msdn.microsoft.com/en-us/library/c09yxbyt.aspx

sukru
  • 2,229
  • 14
  • 15
5

Using Decimal.Parse, you can pass a System.Globalization.NumberStyles to control how strings are parsed. This will let you convert currency strings back to decimals easily. Unfortunately NumberStyles does not support percentages, so you'll still have to strip the percentage symbol out separately.

        Decimal percent = 55.76M;
        String strPercent = String.Format("{0:0.0}%", percent);
        Decimal dollars = 33.5M;
        String strDollars = String.Format("{0:C}", dollars);

        Decimal parsedDollars = Decimal.Parse(strDollars, NumberStyles.Currency);

        Decimal parsedPercent = Decimal.Parse(
            strPercent.Replace(
                NumberFormatInfo.CurrentInfo.PercentSymbol,
                String.Empty));

See the NumberStyles documentation for more info.

Ergwun
  • 12,579
  • 7
  • 56
  • 83
  • Awesome! Thank you so much. So what is the difference between this and using Convert.ToDecimal(StrDollars)? When should I Convert and when should I use Parse? Thanks so much! – Lifes Apr 11 '11 at 04:25
  • Convert.ToDecimal will convert null to zero, Decimal.Parse will throw an exception if passed null. I'd prefer to use Decimal.Parse, and make the handling of a null argument explicit. You can use Decimal.TryParse if your string may be null or badly formatted. Also, Convert.ToDecimal does not support formatting options as you originally requested. I'd stick with Decimal.Parse or Decimal.TryParse, and avoid Convert.ToDecimal entirely. – Ergwun Apr 11 '11 at 12:03