14

I need convert a String to a decimal in C#, but this string have different formats.

For example:

"50085"

"500,85"

"500.85"

This should be convert for 500,85 in decimal. Is there is a simplified form to do this convertion using format?

3
  • Decimal doesn't store in the format of "500,85". Are you asking for a pair of Decimals? Commented May 11, 2011 at 11:19
  • 2
    @myermian: Well, it could, depending on your culture/locale settings. Not everyone represents decimal values the same way. In this example, 500,85 might be equivalent to 500.85. Commented May 11, 2011 at 11:36
  • 1
    Could 50.865,85 be a possibility in your string ? Commented May 11, 2011 at 11:54

7 Answers 7

25

Some cultures use a comma to indicate the floating point. You can test this with the following code on an aspx page:

var x = decimal.Parse("500,85");
Response.Write(x + (decimal)0.15);

This gives the answer 501 when the thread culture has been set to a culture that uses the comma as floating point. You can force this like so:

var x = decimal.Parse("500,85", new NumberFormatInfo() { NumberDecimalSeparator = "," });
Sign up to request clarification or add additional context in comments.

Comments

18

While decimal.Parse() is the method you are looking for, you will have to provide a bit more information to it. It will not automatically pick between the 3 formats you give, you will have to tell it which format you are expecting (in the form of an IFormatProvider). Note that even with an IFormatProvider, I don't think "50085" will be properly pulled in.

The only consistent thing I see is that it appears from your examples that you always expect two decimal places of precision. If that is the case, you could strip out all periods and commas and then divide by 100.

Maybe something like:

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

1 Comment

I dont find any format to resolve my problem. I use this implementation and add decimal places. Thanks
6

This will work, depending on your culture settings:

string s = "500.85";
decimal d = decimal.Parse(s);

If your culture does not by default allow , instead of . as a decimal point, you will probably need to:

s = s.Replace(',','.');

But will need to check for multiple .'s... this seems to boil down to more of an issue of input sanitization. If you are able to validate and sanitize the input to all conform to a set of rules, the conversion to decimal will be a lot easier.

3 Comments

+1 for mentioning input sanitization... -1 for not handling "50085". Balances out to no vote :)
I fear there could also be a input like 50.865,85
@Chris, 50085 would result in 50085 after decimal.Parse... I'd accept the no vote though, as I don't think this fully answers the OPs question. :)
5

Try this code below:

string numValue = "500,85";
System.Globalization.CultureInfo culInfo = new System.Globalization.CultureInfo("fr-FR");
decimal decValue;
bool decValid = decimal.TryParse(numValue, System.Globalization.NumberStyles.Number, culInfo.NumberFormat, out decValue);
if (decValid)
{
    lblDecNum.Text = Convert.ToString(decValue, culInfo.NumberFormat);
}

Since I am giving a value of 500,85 I will assume that the culture is French and hence the decimal separator is ",". Then decimal.TryParse(numValue, System.Globalization.NumberStyles.Number, culInfo.NumberFormat,out decValue); will return the value as 500.85 in decValue. Similarly if the user is English US then change the culInfo constructor.

Comments

3

This is a new feature called Digit Grouping Symbol.

Steps:

  1. Open Region and Language in control panel
  2. Click on Additional setting
  3. On Numbers tab
  4. Set Digit Grouping Symbol as custom setting. Change comma; replace with (any character as A to Z or {/,}). Digit Grouping Symbol=e;

Example:

string checkFormate = "123e123";
decimal outPut = 0.0M;
decimal.TryParse(checkFormate, out outPut);
Ans: outPut=123123;

Comments

2

There are numerous ways:

  1. System.Convert.ToDecimal("232.23")
  2. Double.Parse("232.23")
  3. double test; Double.TryParse("232.23", out test)

Make sure you try and catch...

Comments

1

Try This

 public decimal AutoParse(string value)
    {
        if (Convert.ToDecimal("3.3") == ((decimal)3.3))
        {
            return Convert.ToDecimal(value.Replace(",", "."));
        }
        else
        {
            return Convert.ToDecimal(value.Replace(".", ","));
        }

    }

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.