eyalb
eyalb

Reputation: 3022

Converting string of decimal to list

When tring to convert string of decimal "0,0,0,0,0,0,8555,127875,-180000,152000,55000,3.84,648000" I get an error when one of the items is negative

Input string was not in a correct format.

System.Globalization.NumberStyles style = System.Globalization.NumberStyles.AllowDecimalPoint | System.Globalization.NumberStyles.AllowThousands | System.Globalization.NumberStyles.AllowExponent ;
String t = "0,0,0,0,0,0,8555,127875,-180000,152000,55000,3.84,648000";
List<decimal> prices = t.Split(',').Select(n => decimal.Parse(n, style)).ToList();

Upvotes: 1

Views: 1327

Answers (2)

Martheen
Martheen

Reputation: 5580

Add System.Globalization.NumberStyles.AllowLeadingSign flag.

System.Globalization.NumberStyles style = System.Globalization.NumberStyles.AllowDecimalPoint | System.Globalization.NumberStyles.AllowThousands | System.Globalization.NumberStyles.AllowExponent | System.Globalization.NumberStyles.AllowLeadingSign;
String t = "0,0,0,0,0,0,8555,127875,-180000,152000,55000,3.84,648000";
List<decimal> prices = t.Split(',').Select(n => decimal.Parse(n, style)).ToList();

Upvotes: 4

Syed Mhamudul Hasan
Syed Mhamudul Hasan

Reputation: 1349

Try this

String t = "0,0,0,0,0,0,8555,127875,-180000,152000,55000,3.84,648000";

String[] list = t.Split(',');
List<Decimal> decimals = new List<decimal>();
foreach (string s in list)
{
    decimals.Add(Convert.ToDecimal(s));
}

or

List<Decimal> decimals = t.Split(',').Select(x => Convert.ToDecimal(x)).ToList();

Upvotes: 0

Related Questions