NoChance
NoChance

Reputation: 5752

String formating unexpected result

Why are these 2 lines show different values? Is it because {0:18}"? Why? Thanks.

Console.WriteLine(value.ToString("C", CultureInfo.GetCultureInfo("da-DK")));           //-12,46 kr.
Console.WriteLine("{0,-18}",value.ToString("C"), CultureInfo.GetCultureInfo("da-DK")); //($12.46)

Upvotes: 1

Views: 96

Answers (2)

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186668

The culture parameter treats differently in these calls; for the 1st fragment

Console.WriteLine(value.ToString("C", CultureInfo.GetCultureInfo("da-DK")));

we have value converted to string treating value as being currency ("C") of Danemark (CultureInfo.GetCultureInfo("da-DK")). On the contrary for

Console.WriteLine("{0,-18}",value.ToString("C"), CultureInfo.GetCultureInfo("da-DK"));

we have efficiently String.Format ("{0,-18}") call with two parameters:

  1. value.ToString("C") - value as default culture (not necessary da-DK) currency, so it can be, say, "15.47$"
  2. CultureInfo.GetCultureInfo("da-DK") which is ignored (no {1} in the format)

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1500375

Is it because {0:18}?

No. In the first case, you're formatting your value as string a using the "C" format specifier, and using the Danish culture.

In the second case, you're formatting your value as string a using the "C" format specifier using the default culture... and then including that string value in another format operation. You're passing the Danish culture as a second, unused format argument, but even if you passed it in the right place, it would be irrelevant by that point, as when you format a string, it always just stays as it is, regardless of culture.

I suspect you actually want this:

string text = value.ToString("C", CultureInfo.GetCultureInfo("da-DK"));
Console.WriteLine("{0,-18}", text);

Or to do all the string formatting in one operation:

string text = string.Format(CultureInfo.GetCultureInfo("da-DK"), "{0,-18:C}", value);
Console.WriteLine(text);

(As far as I can tell, Console.WriteLine has no overload permitting the culture to be specified.)

Upvotes: 3

Related Questions