0

I have a decimal value 14780 in En-US locale , the expected output in German is 14.780. But the trailing zero is not taking.

Decimal.Parse(string.Format("{0:n0}", 14780),System.Globalization.CultureInfo.InvariantCulture)

Observed output : 14.78

Archana
  • 1
  • 2

2 Answers2

0
  1. System.Globalization.CultureInfo.InvariantCulture is not the same as German (de-DE). When parsing and converting to string always use the same culture by specifying that culture in the Parse/TryParse and also the Format methods. Using English (invariant) for one and German for the other will lead to unexpected results because the decimal and comma have opposite meaning between the cultures. Never assume the thread supplies the culture unless you know what that culture is and it cant be changed.
  2. A trailing 0 would never be dropped from the left side of the decimal unless you are using scientific notation in which case even then it is preserved but using an exponent. Maybe you are did not type your question correctly and are referring to the right side (fractional part) of the number?

Code sample:

var value = 14780M;
var strValue = string.Format(System.Globalization.CultureInfo.GetCultureInfo("de-DE"), "{0:n0}", value)
// strValue is equal to "14.780"

Here is your code above showing that it works when using the same culture but breaks when you mix cultures.

// OK - using InvariantCulture for both
var culture = System.Globalization.CultureInfo.InvariantCulture;
Console.WriteLine(Decimal.Parse(string.Format(culture, "{0:n0}", 14780), culture));

// OK - using de-DE for both
culture = System.Globalization.CultureInfo.GetCultureInfo("de-DE");
Console.WriteLine(Decimal.Parse(string.Format(culture, "{0:n0}", 14780), culture));

// FAIL - mixing de-DE and InvariantCulture
culture = System.Globalization.CultureInfo.GetCultureInfo("de-DE");
Console.WriteLine(Decimal.Parse(string.Format(culture, "{0:n0}", 14780), System.Globalization.CultureInfo.InvariantCulture));

See Fiddle

Igor
  • 60,821
  • 10
  • 100
  • 175
0

decimal type does not store thousands seperators. But you can reconstitute them again when converting the decimal back to a string.

decimal deci = Decimal.Parse(string.Format("{0:n0}", 14780), System.Globalization.CultureInfo.InvariantCulture); // 14780
string str = string.Format("{0:n0}", deci); // 14.780

.NET String.Format() to add commas in thousands place for a number.

.net Fiddle

Community
  • 1
  • 1
Georg Patscheider
  • 9,357
  • 1
  • 26
  • 36