3

I'd like to format my number as a percent value with an always visible sign.

To format it as a percent value I can do:

string.Format("{0:P2}", 1.45);

For visible signs I'll do:

string.Format("{0:+#.##;-#.##;0}", 1.45);

Any way to combine the two?

7
  • Please prefer string interpolation over string.Format. The readability improvements are dramatic. Commented May 17, 2017 at 13:40
  • @AluanHaddad I would if I was working in a newer .NET. Commented May 17, 2017 at 13:41
  • Well, upgrade! You can downlevel many language features to older runtimes besides. Here is a helpful reference on format specifiers: msdn.microsoft.com/en-us/library/dwhawy9k(v=vs.110).aspx P.S: Google is my friend and yours too :) Commented May 17, 2017 at 13:42
  • I would argue the easiest option is something like this (1.45 < 0 ? "-" : "+") + String.Format("{0:P2}", 1.45);, provided your .NET version predicament Commented May 17, 2017 at 13:43
  • I would upgrade if i could :))) Can you refrain from posting if you're not helping with the original question? Commented May 17, 2017 at 13:44

1 Answer 1

4

You probably just want to add % to custom format:

string.Format("{0:+#.##%;-#.##%;0}", 1.45); // output +145%
2
  • No need to repeat the # twice after the . . Why you don't just use it like this string.Format("{0:+#.#%;-#.#%;0}", 1.45); Commented May 17, 2017 at 13:55
  • @HosseinNarimaniRad, tbh I was simply copy-pasting OP input. But what you suggest is not the same #.# and #.## results are different, try yourself with 1.45678.
    – Sinatr
    Commented May 17, 2017 at 13:58

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.