1

I have a very strange problem in C# application. The problem is consistent, but only on one remote computer. The data below contains decimal numbers. I perform the following simplified operation:

Array data = (Array)get_data(); // array of decimals
StringBuilder sb = new StringBuilder();
sb.Append(data.GetValue(0));
string s = sb.ToString();

This converts numbers like 14.62 into "14,62", i.e comma instead of dot. Later, when I parse this string into double, it generates errors. How to prevent this?

Please note, that I don't have access to that remote computer. I can only adjust the program's code, and then send a new installer.

1

3 Answers 3

3
StringBuilder sb = new StringBuilder();

sb.Append(((double)data.GetValue(0)).ToString(CultureInfo.InvariantCulture));

See: http://msdn.microsoft.com/en-us/library/shxtf045(v=vs.110).aspx

Sign up to request clarification or add additional context in comments.

2 Comments

Why the invariant culture? If this value is displayed, wouldn't it make more sense to pass CultureInfo.CurrentCulture?
Ahh I was assuming the ToString and Parse were happening in the same locale, which of course wouldn't be a problem. If this value is changing locale's, then that would explain it.
3

You are getting the different output because of the remote computer's culture. Some culture uses , as decimal separators and some uses .. To override that you have to call ToString with CultureInfo.InvariantCulture. You can also use the following one liner which would give you the same thing.

string s = string.Join(",", 
                        data.OfType<decimal>()
                        .Select(r=> r.ToString(CultureInfo.InvariantCulture)));

(I assumed that you needed a delimiter separated string for your data elements, since you were using StringBuilder)

1 Comment

Yes, you assumed correctly, and it's great to know how to convert the whole array. But in my case it's a 2-dimensional array where the first column is decimal and the second - integers. (this is how it comes from an external API). Anyway, many thanks!
1

I had a similar issue I cloned the Culture Invariant( makes it en-US)

    private string ConvertPriceFormat(double amount)
{
    string price = string.Empty;

    // NumberFormatInfo of InvariantCulture thousandseparator = "," DecimalSeparator="."
    NumberFormatInfo nfi = (NumberFormatInfo)CultureInfo.InvariantCulture.NumberFormat.Clone();

    // make Changes for the Injection
    nfi.NumberGroupSeparator = "";

    // Format the price with the defined format
    price = amount.ToString("n", nfi);

    return price;
}

Just need to change it to go from string to double

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.