Cerealkiller050
Cerealkiller050

Reputation: 53

Must String.format() declare culture invariance?

Recently new job and got a question regarding an error in the software from a customer. The error is "Conversion from string '0.5' to type 'double' is not valid."

I believe I have found the offending line. Because the customer is in France and has his computers settings all in french (numbering system, language,...) that the "0.5" can't be casted to french number version of "0,5" The French system has no decimals anywhere in their numbers. So, if string.format sees "0.5" it won't know what to do, because there is no '.' character to be casted to double in french culture settings. Am I right here?

context.Append(String.Format("{0} {1} exceeds fine {2} limit of {3:N0}", _
       context.OccupancyState, context.Size, _
       Reg.Alert.ToLower, context.Limit))

Where context.Size holds the "0.5" string.

Does format.string take into account the culture settings, or am I missing something here?

EDIT:

Just tried it on french windows VM, and (unfortunately) it was able to parse it as "0,5" successfully...So maybe that isn't the problem?

Upvotes: 1

Views: 1073

Answers (3)

ChrisF
ChrisF

Reputation: 137148

String formatting and parsing does take the computer's culture/locale into account, so if you know that all your numbers are going to output with a decimal point and entered in the same format then you will have to pass an invariant culture to the formatting and parsing methods.

Though you say context.Size holds the string "0.5". This doesn't make sense as it's the second argument and so will replace the {1} in the string.Format.

What is probably going wrong is that the code is attempting to context.Limit to a decimal to output with the {3:N0} formatting. If this string is "0.5" then that would cause the error on French machines (or any PC with a decimal comma) as that's not a valid numeric with that format.

So either store your numbers as numbers or don't try and format your already formatted strings as numbers.

Upvotes: 1

ToXyS
ToXyS

Reputation: 31

CultureInfo culture = new CultureInfo("en-US");
context.Append(String.Format(culture, "{0} {1} exceeds fine {2} limit of {3:N0}", _
       context.OccupancyState, context.Size, _
       Reg.Alert.ToLower, context.Limit))

Upvotes: 2

Tim Schmelter
Tim Schmelter

Reputation: 460108

You need to convert the string to a double first, otherwise String.Format will just concat the string without any formatting.

double d = double.Parse(context.Size, CultureInfo.InvariantCulture);
string formatted = String.Format("{0} {1} exceeds fine {2} limit of {3:N0}"
                                 , context.OccupancyState, context.Size
                                 , Reg.Alert.ToLower, context.Limit);

Now string.Format will use System.Globalization.CultureInfo.CurrentCulture when it formats the double to a string again.

Upvotes: 0

Related Questions