2

Im using Visual Studio 2010. My code has a strange behavior

With this code I can parse xml file.

XDocument document = XDocument.Load("http://www.studiovincent.net/list.xml");
XElement resourcesElement = document.Root.Element("resources");
XElement resourceElementVincent = (from resourceElement in resourcesElement.Elements("resource")
                                           where resourceElement.Elements("field").Single(fieldElement => fieldElement.Attribute("name").Value == "name").Value == "Vincent"
                                           select resourceElement).Single();

decimal tasso = Math.Round(decimal.Parse(resourceElementVincent.Elements("field").Single(fieldElement => fieldElement.Attribute("name").Value == "age").Value) / Convert.ToInt64(1.00E+006), 6);


string gigi = Math.Round(41 * tasso, 4).ToString();
Console.WriteLine("{0}", gigi);
Console.ReadLine();

All work correctly, until I change regional options. If I select italian:

enter image description here

This is OUTPUT: 0,0013

enter image description here

If I select United States in regional options, this is OUTPUT: 0.0000

enter image description here

I dont know how to solve this issue.

Thanks in advance.

Vincenzo Lo Palo
  • 1,341
  • 5
  • 19
  • 32
  • Are you purposely attempting to shorten it to four zeros? ie.e, `0000`? It could be that there is a rounding issue somewhere, but it is cutting it off due to length of allowed output. See if you can increase the length of the output, you might find "hidden" values that weren't being displayed before. If that's the case, change the way the output is parsed for the respective region. – plast1K Jan 24 '13 at 21:58

3 Answers3

3

decimal.Parse(string) uses the current system format; thus

decimal.Parse(resourceElementVincent.Elements("field")
       .Single(fieldElement => fieldElement.Attribute("name").Value == "age")
       .Value)

will return zero when Vincent's age is set to 0.27 and the current culture is Italian (where the NumberDecimalSeparator is a comma).

However, you could use the decimal.Parse(string, IFormatProvider) method instead, passing the InvariantCulture (where the NumberDecimalSeparator is a period):

decimal.Parse(resourceElementVincent.Elements("field")
       .Single(fieldElement => fieldElement.Attribute("name").Value == "age")
       .Value, CultureInfo.InvariantCulture);

MSDN documentation here.

Edmund Schweppe
  • 4,992
  • 1
  • 20
  • 26
1

My guess is that the parsing of 1.00E+006 is dependent upon the current region.

mbeckish
  • 10,485
  • 5
  • 30
  • 55
-1

This is normal! European languages use decimal points as commas, and vice-versa. If you want to use one or the other consistently, you can set a specific culture in conjunction with String.Format, as seen here:

Format string by CultureInfo

Community
  • 1
  • 1
Kenogu Labz
  • 1,094
  • 1
  • 9
  • 20