C# Percent ("P") Format
In this chapter you will learn:
Description
The percent ("P") specifier formats a number in a percentage.
Item | Value |
---|---|
Format specifier | "P" or "p" |
Supported by | All numeric types. |
Result | Number multiplied by 100 and displayed with a percent symbol. |
Precision specifier | indicates the desired number of decimal places. |
Default precision specifier | Defined by System.Globalization.NumberFormatInfo. |
Example,
Value | Format | Formatted |
---|---|---|
1 | ("P", en-US) | 100.00 % |
1 | ("P", fr-FR) | 100,00 % |
-0.39678 | ("P1", en-US) | -39.7 % |
-0.39678 | ("P1", fr-FR) | -39,7 % |
The NumberFormatInfo properties controls the formatting.
- PercentPositivePattern
- PercentNegativePattern
- NegativeSign
- PercentSymbol
- PercentDecimalDigits
- PercentDecimalSeparator
- PercentGroupSeparator
- PercentGroupSizes
Example
using System;// w ww. j av a2 s . co m
using System.Globalization;
class MainClass
{
static void Main()
{
double number = .2468013;
Console.WriteLine(number.ToString("P", CultureInfo.InvariantCulture));
// Displays 24.68 %
Console.WriteLine(number.ToString("P",
CultureInfo.CreateSpecificCulture("hr-HR")));
// Displays 24,68%
Console.WriteLine(number.ToString("P1", CultureInfo.InvariantCulture));
// Displays 24.7 %
}
}
The code above generates the following result.
Next chapter...
What you will learn in the next chapter: