Decimal Parse and CultureInfo for Decimal separator
I've looked around this forum, and the rest of the internet, but my code is not working. Here is the problem:
I read XML files that are in en-US culture. The decimal separator is a dot ".".
Given the string "123.45", I want to convert the separator from a dot, to a comma. The current code doesn't work.
String tmp = "123.45";
System.Globalization.CultureInfo myInfo = System.Globalization.CultureInfo.CurrentUICulture;
/****The above line returns my culture, es-ES where the number separator is ","***/
System.Windows.Forms.MessageBox.Show("New value: "+ Decimal.Parse(test, myInfo));
/***The above line displays the result "12345"***/
I have a lot of variables to put through this process so parsing strings isn't really useful at this point.
Any help is appreciated.
charlybones
Junior Poster in Training
77 posts since Jan 2011
Reputation Points: 16
Solved Threads: 16
Of course it doesn't work, you are parsing en-US as es-ES. You need to do the parse first, then convert cultures for output.
String tmep = "123.45";
Decimal value = Decimal.Parse(test, system.Globalization.CultureInfo.InvariantCulture);
System.Windows.Forms.MessageBox.Show("New value: " + value);
This should work, it's hard to test because my UI culture is en-US :)
Momerath
Nearly a Senior Poster
3,386 posts since Aug 2010
Reputation Points: 1,232
Solved Threads: 558
Mine is nl-BE also with comma as decimal point.
The MessageBox gives 123,45 (with comma) if I execute the OPs code.
Perhaps try something like this?
Decimal d = Decimal.Parse(tmp, myInfo); //123.45
string str = d.ToString(CultureInfo.GetCultureInfo("es-ES").NumberFormat);//123,45
ddanbe
Senior Poster
3,829 posts since Oct 2008
Reputation Points: 2,070
Solved Threads: 661
Try this:
string a = "12.34";
decimal b = Convert.ToDecimal(a, System.Globalization.CultureInfo.InvariantCulture);
Mitja Bonca
Nearly a Posting Maven
2,485 posts since May 2009
Reputation Points: 641
Solved Threads: 474
Thanks guys, InvariantCulture solved the problem.
Regards.
charlybones
Junior Poster in Training
77 posts since Jan 2011
Reputation Points: 16
Solved Threads: 16