问题描述:

I'm currently doing an app, that needs to be able to work with the US number layout (123,456.78) as well as with the German layout (123.456,78).

Now my approach is to use NumberFormatInfo.InvariantInfo about like this:

temp = temp.ToString(NumberFormatInfo.InvariantInfo);

this works great when for example reading a number from a textbox. When System is set to English format it will take the . as separator, when it's set to German it will use the ,.

So far so good....but here's the problem: I have a device that returns info in the American format, and that won't change (transmitted via RS232). So I receive something like 10.543355E-00.

Now when on German setting the . will be discarded since it's just the group separator

and the number I will end up with is 10543355....which is a lot more :)

I tried with the same technique thinking this would make the whole thing kind of 'cultureless' to be able to process it independently from the system language but it didn't work :)

I hope you can maybe help me here...I'd love to use a way without having to implement the whole culture stuff etc since all I need here is really numbers that get calculated the right way.

网友答案:

You should use CultureInfo.InvariantCulture when parsing strings from the device. This will cause it to use the invariant culture, which has the US rules for decimal separation.


Edit in response to comments:

The issue is not when you call .ToString(), but rather when you read the string from the device, and convert it to a number:

string inputFromRS232Device = GetDeviceInput();
double value;

// You need this when converting to the double - not when calling ToString()
bool success = double.TryParse(
                          inputFromRS232Device, 
                          NumberStyles.Float, 
                          CultureInfo.InvariantCulture, 
                          out value);
相关阅读:
Top