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
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
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.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
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.