Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
504 views
in Technique[技术] by (71.8m points)

c# - What is the percentage format string to always display the sign?

I want to display 0.12345 as "+12.3%". Format string "P1" or "p1" gives "12.3%". I have tried both "+P1" and "+p1" to no avail.

string sFoo = 0.12345.ToString("P1");

Update

I should have emphasized that I always want the proper sign, not "+". If the number is -0.12345, "P1" works exactly as I want: "-12.3%".


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Not quite using P1, but same result:

0.12345.ToString("+#.#%;-#.#%");

If you prefer at least one leading digit (e.g. "+0.23%" instead of "+.23%"):

0.12345.ToString("+0.#%;-0.#%"));

Same for trailing digits (e.g. "+14.0%" instead of "+14%"):

0.12345.ToString("+0.0%;-0.0%"));

Reference: https://docs.microsoft.com/en-us/dotnet/standard/base-types/custom-numeric-format-strings#the--section-separator


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...