Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String.Format not converting integers correctly in arabic

I have a problem with String.Format. The following code formats the string correctly apart from the first integer. Current culture is set to Iraqi arabic (ar-IQ):

int currentItem= 1;
string of= "من";
int count = 2;
string formatted = string.Format(CultureInfo.CurrentCulture, "{0}{1}{2}", currentItem, of, count);

The text is formatted right to left and the 2 is converted to an arabic digit, but the 1 isn't.

Any ideas?

like image 862
Ken Jackson Avatar asked Jun 16 '10 16:06

Ken Jackson


2 Answers

The default behaviour for converting numeric values is "Context", which basically means if a number is proceeded by Arabic they display in Arabic (or another "non-Latin" character), if they're not then they display in "standard" European numbers.

You can change that behaviour quite easily though:

var culture = CultureInfo.CurrentCulture;
culture.NumberFormat.DigitSubstitution = DigitShapes.NativeNational; // Always use native characters
string formatted = string.Format(culture, "{0:d}{1:d}{2:d}", currentItem, of, count);

That should work as you expect - more details on MSDN.

like image 190
Steven Robbins Avatar answered Nov 15 '22 12:11

Steven Robbins


I couldn't get either of the other answers to work. This worked for me:

string sOriginal = "1 of 2";
var ci = new CultureInfo("ar-IQ", false);
var nfi = ci.NumberFormat;
string sNative = ReplaceWesternDigitsWithNativeDigits(sOriginal, nfi).Replace("of", "من");

...

private static string ReplaceWesternDigitsWithNativeDigits(string s, NumberFormatInfo nfi)
{
    return s.Replace("0", nfi.NativeDigits[0])
        .Replace("1", nfi.NativeDigits[1])
        .Replace("2", nfi.NativeDigits[2])
        .Replace("3", nfi.NativeDigits[3])
        .Replace("4", nfi.NativeDigits[4])
        .Replace("5", nfi.NativeDigits[5])
        .Replace("6", nfi.NativeDigits[6])
        .Replace("7", nfi.NativeDigits[7])
        .Replace("8", nfi.NativeDigits[8])
        .Replace("9", nfi.NativeDigits[9]);
}
like image 23
tjsmith Avatar answered Nov 15 '22 13:11

tjsmith