Friday 22 May 2009

Stop a Number Being Multiplied by 100 When the '%' Custom Number Format Character is Used

When formatting a number with the % character the value is multiplied by 100 before it is displayed. This is not always the desired behaviour as percentage values are often stored as integers. I.E 15% might be stored in a database as 15. The easiest way to get the character to work in this way is simply to place a single quote character ' before the percentage sign. A quick example follows.
static void Main(string[] args)
{
var value = 15;
Console.WriteLine("{0:#,##0.00%}", value);
Console.WriteLine("{0:#,##0.00'%}", value);
Console.ReadLine();
}

Gives the output:
1,500.00%
15.00%

No comments:

Post a Comment