Search code examples
.netdoubleglobalizationtostring

.NET: Is it possible to change the format used by double.ToString()?


I have some third party code, that invokes double.ToString(). My problem, is that the default double.ToString() implementation replaces the decimal dot with a comma, like so:

49.99.ToString() == "49,99"

This happens, because the default double.ToString() uses CultureInfo.CurrentCulture whereas I need it to be CultureInfo.InvariantCulture. Indeed, observe:

49.99.ToString(CultureInfo.InvariantCulture) == "49.99"
49.99.ToString(CultureInfo.CurrentCulture) == "49,99"

Is there a way to change the current culture to be the invariant one, so that double.ToString() work as I need it to?

I would like to avoid as much as possible tinkering with the third party code, so please, do not suggest me just using the ToString(IFormatProvider) overload instead of the default ToString().

Thanks.


Solution

  • You could set the culture info of the current thread which is what is used by default:

    Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
    

    and if this is a web application you could set the culture and uiCulture attributes of the <globalization> element in your web.config.