3

I have installed C# application under Spanish MS Windows Server.

So this code is working in a wrong way.

decimal? top = 80.0m;
double convertedTop = (double)decimal.Parse(top.ToString(), CultureInfo.InvariantCulture); 

convertedTop is 80000 but it should be 80.0

Ionică Bizău
  • 109,027
  • 88
  • 289
  • 474
NoWar
  • 36,338
  • 80
  • 323
  • 498

1 Answers1

7

Don't do that.

Your code is extremely inefficient.

You should change it to

double convertedTop = Convert.ToDouble(top);

If the compile-time type of top is decimal or decimal? (as opposed to object or IConvertible or ValueType), you can use an even-more-efficient compile-time cast:

double convertedTop = (double)top;

To answer the question, top.ToString() is culture-sensitive.
You need to pass CultureInfo.InvariantCulture there too.
Nullable<T> doesn't lift ToString(IFormatProvider), so you'll need to do that on Value and handle null explicitly.

Community
  • 1
  • 1
SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
  • Thank you! Could u explan difference between (double) and Convert.ToDouble() please? – NoWar Mar 05 '13 at 18:09
  • 1
    @Peretz: `(double)` is a compile-time cast. When used on an object, it can only perform an unboxing conversion. http://blogs.msdn.com/b/ericlippert/archive/2009/03/19/representation-and-identity.aspx. `Convert.To*()` are complicated methods that essentially perform a `switch()` on the type of the argument and convert as appropriate. – SLaks Mar 05 '13 at 18:11