Reputation: 97
My system is id-ID, using ',' as decimal separator. I have problems with data in en-US, I want to convert it to id-ID and then back to en-US :
List<string> list = new List<string>(){"0.14","223.54"}; // en-US
list[0] = Convert.ToDecimal(list[0], CultureInfo.InvariantCulture).ToString();
MessageBox.Show("list[0] = " + list[0]); //display "0,14", it is ok!
MessageBox.Show("list[1] = " + list[1]); //display "223,54", it is ok!
Now I want to change it back to US culture, I can simply use Replace to change ',' back to '.' as US culture.
MessageBox.Show("list[0] = " + list[0].Replace(",", ".")); //displays "0.14"
But it is not an elegant way to handle it, I wish I can handle it with CultureInfo, so I try the following statements but can't work!
CultureInfo us = new CultureInfo("en-US");
list[0] = Convert.ToDecimal(list[0], us).ToString();
list[1] = Convert.ToDecimal(list[1], us).ToString();
MessageBox.Show("list[0] = " + list[0]); //display "14", the decimal separator is missing!
MessageBox.Show("list[1] = " + list[1]); //display "223,54", nothing changed!
Upvotes: 0
Views: 1321
Reputation: 854
en-US culture uses comma as a number group separator. This a reason of the mistake. Better approach is to store decimal as decimal. Use required culture when you output data:
List<string> stringList = new List<string>() { "0.14", "223.54" };
List<decimal> list = stringList.Select(Convert.ToDecimal).ToList();
MessageBox.Show(list[0].ToString(CultureInfo.InvariantCulture));
MessageBox.Show(list[0].ToString(new CultureInfo("en-US")));
MessageBox.Show(list[0].ToString(new CultureInfo("id-ID")));
Upvotes: 1