Convert currency string to decimal?
How about this, but only works for one string value. So you need to get your string split
by $
and then do the conversion while saving into the array
or list
using System.Globalization;
//rest of your code
string str = "$50,550.20";
decimal decval;
bool convt = decimal.TryParse(str, NumberStyles.Currency,
CultureInfo.CurrentCulture.NumberFormat, out decval);
if (convt)
Console.WriteLine(decval);
Console.ReadLine();
Here is a simpler solution:
public static decimal ToDecimal(this string str)
{
return decimal.Parse(str, NumberStyles.Currency);
}
and the unit test:
[Test]
public void ToDecimal_Convert_String_To_Decimal()
{
Assert.AreEqual(1234M, "1234".ToDecimal());
Assert.AreEqual(-1234.56M, "$(1,234.56)".ToDecimal());
Assert.AreEqual(1234.56M, "$1,234.56".ToDecimal());
}
Here is a method that most closely resembles the code you've provided
public static decimal Parse(string input)
{
return decimal.Parse(Regex.Replace(input, @"[^\d.]", ""));
}
Here is an option that will support negative numbers, and will stop if it finds a second period value, thus reducing the number of strings it returns that are not valid decimal
values. It also has a few other modifications not seen in the OP to handle additional cases your current code doesn't.
public static decimal Parse(string input)
{
return decimal.Parse(Regex.Match(input, @"-?\d{1,3}(,\d{3})*(\.\d+)?").Value);
}