Display format string, int to percent

2019-07-29 20:52发布

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%"

6条回答
smile是对你的礼貌
2楼-- · 2019-07-29 21:19

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.

查看更多
狗以群分
3楼-- · 2019-07-29 21:20

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.

查看更多
劫难
4楼-- · 2019-07-29 21:23

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.

查看更多
乱世女痞
5楼-- · 2019-07-29 21:27

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

查看更多
smile是对你的礼貌
6楼-- · 2019-07-29 21:27

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

查看更多
贪生不怕死
7楼-- · 2019-07-29 21:34

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.

查看更多
登录 后发表回答