52

I have new XmlDocument object, i.g. xml is created during my program...

I want all numeric values in created xml was with dot symbol instead of comma by default.

Can I do something to declare it once, not to parse every decimal value?

I.e. To set up this dot instead of comma somewhere in the beginning and don't worry about this till the end?

svick
  • 214,528
  • 47
  • 357
  • 477
Ksice
  • 2,907
  • 8
  • 38
  • 58
  • If you want a decimal dot in XML but want to use a decimal comma when displaying values to users, you will have to specify it on the spot. There is no "use dot only in xml" setting. – Hans Kesting Feb 06 '12 at 12:34

3 Answers3

109

Try this:

System.Globalization.CultureInfo customCulture = (System.Globalization.CultureInfo)System.Threading.Thread.CurrentThread.CurrentCulture.Clone();
customCulture.NumberFormat.NumberDecimalSeparator = ".";

System.Threading.Thread.CurrentThread.CurrentCulture = customCulture;
bang
  • 4,163
  • 1
  • 20
  • 25
  • 2
    Why not just directly assign NumberDecimalSeperator in CurrentCulture? – Brent Dec 12 '14 at 15:54
  • @Brent Visual Studio shows an error which says "An object reference is required for the non-static field, method, or property 'CultureInfo.NumberFormat'.". So, it is required to create an instance to reach to the related property. – Caglayan DOKME Feb 16 '20 at 08:59
25

You can use value.ToString(CultureInfo.InvariantCulture) to convert your numeric values to strings. Or you can globally change the current culture to a culture that uses the dot as the decimal separator:

Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-US");
Thomas Levesque
  • 270,447
  • 59
  • 580
  • 726
  • `value.ToString(CultureInfo.InvariantCulture)` does not currently work: https://msdn.microsoft.com/en-us/library/29dxe1x2(v=vs.100).aspx – Jonas Mar 31 '16 at 15:28
  • 1
    @Jonas, the link you pointed to is about `String.ToString(IFormatProvider)`. The part about how this parameter is "reserved" doesn't apply to other types, only String – Thomas Levesque Mar 31 '16 at 15:35
  • 1
    In my Version (.NET 4.5) it is `CultureInfo.GetCultureInfo("en-US")`. Works perfectly. – itmuckel Oct 19 '16 at 07:39
  • Yes, works great except I also need GetCulture**Info**. – CodeMonkey Dec 14 '17 at 09:42
  • This is a much better solution for the intended purpose than the accepted answer! – jlapoutre Sep 14 '19 at 10:17
  • Beware also of the group separator - if you print numbers as "N", you will get , (comma) as group separator, which might be not what you want for XML. – JustAMartin Dec 09 '19 at 10:58
8

Use Decimal.ToString(..) with System.Globalization.CultureInfo.InvariantCulture like a paramater applied.

or if you want to do it globaly, use

CurrentCulture to set to always Invariant one, by using Applicaton.CurrentCulture property.

Tigran
  • 59,345
  • 8
  • 77
  • 117