Display format string, int to percent

2019-07-29 21:23发布

问题:

I have some integer values (between 1 and 100) and I want to use them in a progress bar, that has a DisplayFormatString property.

I also want to have the percent symbol '%' in the output string.

The problem is that by using the symbol, it automatically multiplies my value with 100, and it shows my values like 3300% when I wanted them 33%. How may I overcome this?

DisplayFormatString="0%"

回答1:

Try using 0'%' as the DisplayFormatString, (percentage in single quotes) this should help in achieving to append the percentage sign to your number. So you get 33%.

One more thing you could try maybe is 0\\% (not sure if it would work or not) but should work out to the same 33% as you desire.



回答2:

The ProgressBar assumes your input will be between 0 and 1. When you set the DisplayFormatString to "P", this will be displayed as a percentage.



回答3:

The problem lies with your representation of percentage. Usually a percentage is a decimal 0 to 1 where 1 is 100% and 0 is 0%. So if you want to use the standard string.Format you'll have to divide your variable with 100.0 (so your int 33 becomes a decimal 0.33). Something like this:

int progress = 33;
string.Format("{0:F}", progress / 100.0);

If you dont want to use that solution you could check out the MSDN section to find a format that suits your needs.



回答4:

The standard .NET string formatting methods will multiply by 100 when formatting as percentages, as per the documentation. Looks like you'll have to divide your input by 100 or change how it's calculated originally.



回答5:

I had a similar problem while working with Data Annotations, I found it worked when I wrapped the 0 in curly brackets: DataFormatString = "{0}%"



回答6:

As show here: try to use DisplayFormatString="P"