locked
Better way of removing commas RRS feed

  • Question

  • Here is the situation, using C# and VS2005, one has a string that contains a number. Unfortunatley the originator of the string is ouputing commas within the string such as

    "1,234,567.89"

    What is the best way to strip commas from a string?

    Below is a method I have come up with that seems like it is overkill... Can it be replaced with an easier, meaning less code on my side, way of doing it?

    advTHANKSance


    using System.Text;
    using System.Text.RegularExpressions;

    ...

    string value = "1,234,567.89";

    Regex rx = new Regex(@"(?:,?)(?<num>[\d\.]*)(?:$?)",
        RegexOptions.ExplicitCapture |
        RegexOptions.Compiled |
        RegexOptions.Singleline);

    MatchCollection mc = rx.Matches(value);

    if (mc.Count == 0)
        throw new Exception("Regular Expression failure");

    StringBuilder HumptyDumpty = new StringBuilder();

    foreach(Match item in mc)
        if ((item.Success) && (item.Groups.Count > 1))
            if (string.IsNullOrEmpty( item.Groups["num"].Value ) == false)
                HumptyDumpty.Append(item.Groups["num"].Value);


    Console.WriteLine(HumptyDumpty.ToString()); // Returns 1234567.89

    Monday, June 26, 2006 8:29 PM
    Moderator

Answers

  • I am not sure if I am missing something here but won't a

    Double.Parse("1,234,567.89")

    return a double value w/o the commas?

    Monday, June 26, 2006 9:09 PM
  • Hi,

    Lets forget Double.Parse() for a moment (i did not know that it was possible. thanks for the info.). But why do we have to use Regex to do the job? Can't it be accomplised by a simple replace method?

    value = value.Replace(",","");

    or is there anything wrong with this method?

    Thursday, June 29, 2006 6:27 AM

All replies

  • I am not sure if I am missing something here but won't a

    Double.Parse("1,234,567.89")

    return a double value w/o the commas?

    Monday, June 26, 2006 9:09 PM
  • Ahh...can't see the forrest for the trees. Thanks! Didn't think that the parse functionality could handle the commas, but yes it does. Thanks.
    Monday, June 26, 2006 9:49 PM
    Moderator
  • You should specify CultureInfo.InvariantCulture when parsing, just to be on the safe side :).
    Tuesday, June 27, 2006 8:07 AM
  • Hi,

    Lets forget Double.Parse() for a moment (i did not know that it was possible. thanks for the info.). But why do we have to use Regex to do the job? Can't it be accomplised by a simple replace method?

    value = value.Replace(",","");

    or is there anything wrong with this method?

    Thursday, June 29, 2006 6:27 AM
  • why don't you just change each character in the character array (which is a string) ?
    Thursday, June 29, 2006 6:38 AM
  • That would be a way of doing it as well. Thanks.
    Saturday, July 1, 2006 4:37 PM
    Moderator
  • you could also use string.split to split the string into a string[] (arrays) giving it the comma to search and split from.

     

    whilst you can use regex, it is expensive and should only be used when you have large operations executing which require you to do the same thing :)

    Saturday, July 1, 2006 6:10 PM
    Moderator
  •  OmegaMan wrote:
    Here is the situation, using C# and VS2005, one has a string that contains a number. Unfortunatley the originator of the string is ouputing commas within the string such as

    "1,234,567.89"


    What is the best way to strip commas from a string?

    Below is a method I have come up with that seems like it is overkill... Can it be replaced with an easier, meaning less code on my side, way of doing it?

    advTHANKSance


    using System.Text;
    using System.Text.RegularExpressions;

    ...

    string value = "1,234,567.89";

    Regex rx = new Regex(@"(?:,?)(?<num>[\d\.]*)(?:$?)",
        RegexOptions.ExplicitCapture |
        RegexOptions.Compiled |
        RegexOptions.Singleline);

    MatchCollection mc = rx.Matches(value);

    if (mc.Count == 0)
        throw new Exception("Regular Expression failure");

    StringBuilder HumptyDumpty = new StringBuilder();

    foreach(Match item in mc)
        if ((item.Success) && (item.Groups.Count > 1))
            if (string.IsNullOrEmpty( item.Groups["num"].Value ) == false)
                HumptyDumpty.Append(item.Groups["num"].Value);


    Console.WriteLine(HumptyDumpty.ToString()); // Returns 1234567.89

    Hello,

    I guess you complicated things a bit , however you can just replace the ',' occurences with nothing, this will omit all the commas from your input number and you will get what you seek, the following is the way to do it :

    Sample Input  : 1,234,567.89

    Regular Expression : ,

    Replacement String :                                                              note :leave it empty !

    Results of Replace : 1234567.89

    Line to declare your Regex in C# :

    public static Regex regex = new Regex(
        @",",
        RegexOptions.IgnoreCase
        | RegexOptions.CultureInvariant
        | RegexOptions.IgnorePatternWhitespace
        | RegexOptions.Compiled
        );

    this line is generated using Expresso.

    Regards,
    http://CairoCafe.BlogSpot.com

    Sunday, July 2, 2006 10:53 AM
  •  Kareem Shaker wrote:
    Replacement String : note :leave it empty !

    this line is generated using Expresso.



    Hi Kareem,

    Two things I have learned
    1. The ability to do replacements of matches by having nothing passed in.
    2. A tool that would do that. I have been using Rad Software's Reg Ex designer, and by its designed user input, it does not allow for a null replacement as you suggested.
    I am wondering if there is not a meta character in RegEx which will simply drop the non-matches...maybe it is something I need to look into. But thanks for the alternate solution!
    Monday, July 3, 2006 4:20 PM
    Moderator
  • TextBox1.Text = TextBox1.Text.Replace(",", "")

    It replaces comma(,) with nothing.

     

     

     

    Friday, February 2, 2007 5:46 PM
  • pls read the thread carefully b4 posting; the solution (i agree, the best one) has been already offered earlier in the thread.
    Friday, February 2, 2007 6:08 PM