Reputation: 14108
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.
Upvotes: 1
Views: 887
Reputation: 223247
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)
Upvotes: 3
Reputation: 7963
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
Upvotes: 1
Reputation: 116108
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
Upvotes: 3