Home > Net >  Format a percentage using culture info?
Format a percentage using culture info?

Time:09-02

I'm formatting a number as a percentage using the current culture info by doing:

string.Format(CultureInfo.CurrentCulture, "{0:P}", num / 100);

I've tried de-DE and en-US. In the region settings, the number of decimal places is 2. However, the above formatting results in 3 decimal places.

Why is this happening and how do I correctly format the number based on the culture's number format?

CodePudding user response:

Could you try to set the PercentDecimalDigits value in NumberFormatInfo?

CultureInfo.CurrentCulture.NumberFormat.NumberDecimalDigits = 2;
CultureInfo.CurrentCulture.NumberFormat.PercentDecimalDigits = 2;

Reference: https://docs.microsoft.com/en-us/dotnet/api/system.globalization.numberformatinfo.numberdecimaldigits?view=net-6.0

CodePudding user response:

The following line returns the culture's number of digits for percentages.

CultureInfo.CurrentCulture.NumberFormat.PercentDecimalDigits

The value is 3. So the formatting is being applied correctly.

  •  Tags:  
  • c#
  • Related