Q: Percentages

  • Thread starter Thread starter Geoff
  • Start date Start date
G

Geoff

Hi

Can anybody help me with a puzzling thing I've encountered with formating
with percentages. If I have

x = 123

and then use format this with "P" (using the String.Format technique) I get

12300%

not the intended

123%

Can anybody tell me what I've misunderstood?

Thanks in advance

Geoff
 
Geoff,

When formatting a value as a percent, a value in the form 1.23 is formatted
as 123.00%.

You could divide your value by 100 before formatting it to get the result
you are looking for.

Kerry Moorman
 
Well, the description for the "P" numeric format specification does say :
"Displays number multiplied by 100 with a percent sign (%) appended to the
right; always display two digits to the right of the decimal separator."

So, I guess you should divide your value by 100 first, and then use the
Format function.

Dim x As Single = 1.23
Console.WriteLine(Format(x, "Percent"))

There is something to note, here:
Somehow, whenever I try the abbreviated "p" or "P", it never works for me. I
will get "p" as output. But when I enter the whole name "Percent", then it
works. Wonder why this happens !

Regards,
Cerebrus.
 
Cerebrus99,

It is confusing because the various options available for displaying a value
as a percent are subtly different.

For example, here are 3 different options, using ToString, String.Format and
VB's Format function:

Dim value As Single = 1.23

MsgBox(value.ToString("P"))
MsgBox(String.Format("{0:P}", value))
MsgBox(Format(value, "P"))

Kerry Moorman
 
Hi Kerry,

I understand that ToString(), String.Format(), and Format are subtly
different. But are the Format specifications, "p", "P" and "Percent"
different too ? Because, as I mentioned, Format(value, "P") doesn't work for
me.

Regards,

Cerebrus.
 
Thanks Guys. I'll divide by 100.


Kerry Moorman said:
Cerebrus99,

It is confusing because the various options available for displaying a
value
as a percent are subtly different.

For example, here are 3 different options, using ToString, String.Format
and
VB's Format function:

Dim value As Single = 1.23

MsgBox(value.ToString("P"))
MsgBox(String.Format("{0:P}", value))
MsgBox(Format(value, "P"))

Kerry Moorman
 
Cerebrus,

For me, "P" and "p" work for ToSring, String.Format and VB's Format function.

"Percent" does not work for ToString and String.Format, but it does work for
VB's Format function.

Example:

Dim value As Single = 1.23

MsgBox(value.ToString("P"))
MsgBox(String.Format("{0:P}", value))
MsgBox(Format(value, "P"))

MsgBox(value.ToString("p"))
MsgBox(String.Format("{0:p}", value))
MsgBox(Format(value, "p"))

MsgBox(value.ToString("Percent")) '<---- does not work
MsgBox(String.Format("{0:Percent}", value)) '<---- does not work
MsgBox(Format(value, "Percent"))

Kerry Moorman
 
Ah! I tried out all those combinations and our results match ! I must've
been doing something wrong.

Thanks a lot, Kerry.

Regards,
Cerebrus.
 
Back
Top