Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does percentage format specifier multiply by 100?

Why does the 'p' string format for percent multiply the value by 100 before formatting it with the percentage sign?

http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx#PFormatString

The Percent ("P") Format Specifier

The percent ("P") format specifier multiplies a number by 100 and converts it to a string that represents a percentage. The precision specifier indicates the desired number of decimal places. If the precision specifier is omitted, the default numeric precision supplied by the current PercentDecimalDigits property is used.

Is there any way to prevent the value from being multiplied by 100 before formatting? Rather than doing:

(value / 100).ToString("p")
like image 460
Phill Avatar asked Nov 15 '11 05:11

Phill


2 Answers

As to the why, "percent" literally means "out of one hundred", so 50% is mathematically equivalent to 0.50. As to formatting, why not just add a percent sign?

value + "%"

... or something like this:

value.ToString("#.00\\%")
like image 198
StriplingWarrior Avatar answered Oct 25 '22 02:10

StriplingWarrior


You normally work with decimal percents inside of code, like 0.5 and 1.0, but the user likes to see nice whole numbers with a percent sign tacked on the end.

Percent means "out of 100" and clearly your decimal percents are out of 1. Therefore, .ToString("p") multiplies your number by 100 and then appends a percent sign.

It's just the definition.

like image 35
Blender Avatar answered Oct 25 '22 00:10

Blender