Erofh Tor
Erofh Tor

Reputation: 159

c# convert string with comma to number

So i have this input: 3,000,000

And this function return 30000M:

public static decimal? CustomParse(string incomingValue)
{
    decimal val;
    if (!decimal.TryParse(incomingValue.Replace(",", "").Replace(".", ""), NumberStyles.Number, CultureInfo.InvariantCulture, out val))
        return null;
    return val / 100;
}

What the best way to convert this kind on input to numbber ?

EDIT

I also try this::

Regex regex = new Regex(@"\d+");

And the output is 3

Upvotes: 0

Views: 1148

Answers (4)

Akif GÜLEN
Akif GÜLEN

Reputation: 1

Try this

var culture = new CultureInfo("en-US");
            culture.NumberFormat.NumberDecimalSeparator = ",";
            culture.NumberFormat.NumberGroupSeparator = ".";
            decimal amount = 0;
            if (!decimal.TryParse("3,000,000.12", NumberStyles.Any, culture, out amount))
            {

.... }

Upvotes: 0

Max
Max

Reputation: 1715

You could also do this

return Decimal.Parse(incomingValue, new CultureInfo("en-US"));

In en-US '.' is the comma seperator. So it will parse the text correctly.

If culture is set to say "de-DE" 3 would be the expected outcome of the conversion as ',' is the comma seperator.

Your regex however will always give you 3, because it just matches [0-9]+ regular expressions don' t care about your culture settings. If you want a regex to match your number you'd have to use something like

Regex regex = new Regex(@"\d+(,\d+)*");

This would match "123" as well as "123,123" but not "123," or "123." (in witch case it will just match the 123 part).

Upvotes: 2

Alexander
Alexander

Reputation: 9632

Use IFormatProvider in decimal.Parse

var format = new NumberFormatInfo
{
    NumberGroupSeparator = ","
};

decimal res = decimal.Parse("3,000,000", format);

Upvotes: 0

Dave
Dave

Reputation: 2190

You are dividing by 100, so your number won't be 3 millions... Here the solution:

class Program
  {
    static void Main(string[] args)
    {
      decimal? value = CustomParse("3,000,000");
      Console.WriteLine(value);
    }

    public static decimal? CustomParse(string incomingValue)
    {
      decimal val;
      if (!decimal.TryParse(incomingValue.Replace(",", ""), NumberStyles.Number, CultureInfo.InvariantCulture, out val))
        return null;
      return val;
    }
  }

Upvotes: -1

Related Questions