views:

87

answers:

2

I'm writing program in C# for converting between model formats. The model format has numbers as text such as "-0.136222".

I can use System.Convert.ToSingle() to convert this to a floating point number. But here in Germany we use commas as decimal points (-0,136222), and System.Convert picks up on this. Now I have the problem of it not recognizing decimal points since it expects commas.

In a nutshell; We have this: "-0.136222" We get this: -0136222.0f because it expects this: "-0,136222"

Can I tell system to recognize commas as decimal points just for my program? A work around won't work since it needs to be portable (to other countries).

+1  A: 

Use Single.Parse() instead, like this:

Single.Parse("-0.136222", CultureInfo.InvariantCulture);

InvariantCulture is the way to tell the method to parse the string ignoring locale-specific decimal and grouping separators.

Paweł Dyda
Sweet, thats what I needed.
Hannesh
A: 

Leave it as it is. The .Net framework installed on your clients' computers will automatically choose the correct way to parse the data for the country settings that computer is set for. So for example, in continental Europe it will parse your float using commas, but in the USA, UK and others where we use decimal points it will parse the data using decimal points.

Of course, you can override this Culture-specific localisation feature of .Net by using CultureInfo.InvariantCulture (like Pawel has suggested) or any other CultureInfo but this will mean you have to set it specifically for each country you sell your software to. Far better to just let the framework do the work for you :)


Note: It will also mean that a (say) German person working in the USA with his PC set to be localised for Germany will have his floats parsed with commas, as he expects, not with decimal points just because he is located in the USA.

Callum Rogers
I'm sorry I may have made myself unclear. Exactly that was my problem, that .NET chooses for me. The model file format always has decimal places as points, which works good in the USA but not in germany.
Hannesh
@Hannesh: Sorry, I thought you were taking user input rather than reading in a file.
Callum Rogers