kkll
kkll

Reputation: 1

Convert a string to Decimal(10,2)

how can i convert a string to a Decimal(10,2) in C#?

Upvotes: 0

Views: 17232

Answers (3)

Crimsonland
Crimsonland

Reputation: 2204

Try:

string test = "123";

decimal test2 = Convert.ToDecimal(test);

//decimal test2 = Decimal.Parse(test);

//decimal test2;
   // if (decimal.TryParse(test, out result))
//{ //valid }
   //else

   //{ //Exception }

labelConverted.Text = test2.toString();

Decimal Examples

Difference between Convert.ToDecimal(string) & Decimal.Parse(string)

Regards

Upvotes: 0

Piotr Salaciak
Piotr Salaciak

Reputation: 1663

You got to be careful with that, because some cultures uses dots as a thousands separator and comma as a decimal separator.

My proposition for a secure string to decimal converstion:

    public static decimal parseDecimal(string value)
    {
        value = value.Replace(" ", "");
        if (System.Globalization.CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator == ",")
        {
            value = value.Replace(".", ",");
        }
        else
        {
            value = value.Replace(",", ".");
        }
        string[] splited = value.Split(System.Globalization.CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator[0]);
        if (splited.Length > 2)
        {
            string r = "";
            for (int i = 0; i < splited.Length; i++)
            {
                if (i == splited.Length - 1)
                    r += System.Globalization.CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator;
                r += splited[i];
            }
            value = r;
        }
        return decimal.Parse(value);
    }

The loop is in case that string contains both, decimal and thousand separator

Upvotes: 1

Jay Riggs
Jay Riggs

Reputation: 53595

Take a look at Decimal.TryParse, especially if the string is coming from a user.

You'll want to use TryParse if there's any chance the string cannot be converted to a Decimal. TryParse allows you to test if the conversion will work without throwing an Exception.

Upvotes: 4

Related Questions