How can I use a percent % in FormatString without it multiplying by 100?
Asked Answered
H

4

45

I would like to format an integer as a percent without it multiplying by 100 as shown here. Because my source is an int, dividing it first by 100 is not a valid option. Is this possible?

[DisplayFormat(DataFormatString = "{0:#%}")]
Humanitarianism answered 12/5, 2011 at 20:11 Comment(0)
S
69

You can escape the % character:

[DisplayFormat(DataFormatString = @"{0:#\%}")]

Note that there are two ways to use \ as an escape character: if you prefix a string literal with the verbatim symbol (@), then \ characters are included in the string as-is, which means that as part of a format string a single \ will function as an escape character.

Without the @ verbatim symbol, \s are interpreted as escape strings by the compiler and as such need to be escaped themselves, as \\.

Pick one or the other, but not both:

@"{0:#\%}"  -> right
"{0:#\\%}"  -> right
@"{0:#\\%}" -> wrong
Schnell answered 12/5, 2011 at 20:12 Comment(4)
It is workinig fine for non-zero values but when value is zero(0) then only % is showing up. Any help?Awhile
Solved myself with this [DisplayFormat(DataFormatString = @"{0:#0.##\%}")]Awhile
The problem with this can be that you've now lost culture awareness of your formattingMartie
@Martie That's what I was thinking too; I'm surprised more people haven't noticed that. For example, in Turkish the % sign is put before the number and some languages have different spacing rules for percentages.Antoninus
B
37

Put the % outside the {0:..}

[DisplayFormat(DataFormatString = "{0:0.00}%")]
Bandaid answered 28/11, 2012 at 14:56 Comment(2)
@cadmium It's not voted higher, because you cannot use it directly on custom numeric format strings. What I mean by that is methods like ToString() will not allow the { } expression, rather you can only provide the format part that is between {0: and } in the above solution. Methods like String.Format() are okay, however.Ovate
I think this is not the good answer. What if you value is not present? you will get a lonely % char inside you field.Dispatch
I
6

From your linked page:

\ Escape character

Causes the next character to be interpreted as a literal rather than as a custom format specifier.

[DisplayFormat(DataFormatString = "{0:#\\%}")]
Isotron answered 12/5, 2011 at 20:14 Comment(0)
C
0

If the value is 0, the format @"{0:#%}" displays just a %. It should display 0%. So the correct format is

[DisplayFormat(DataFormatString = @"{0:#0\%}")]

There is an extra zero after the hash.

Country answered 6/6, 2022 at 4:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.