Reputation: 1
how can i convert a string to a Decimal(10,2) in C#?
Upvotes: 0
Views: 17232
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();
Difference between Convert.ToDecimal(string) & Decimal.Parse(string)
Regards
Upvotes: 0
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
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