6

I am using the following code to show percentage using String.Format but I also want to limit the number of significant figures to 2, the two don't seem to play well together. How can I get the two working together properly?

String.Format("% Length <= 0.5: {0:0%}", m_SelectedReport.m_QLT_1);

So what I ideally want is something like this

double d1 = 1234;
double d2 = 0.1234;

//Output of d1 -> 12
//Output of d2 -> 0.12
Jonathan Leffler
  • 666,971
  • 126
  • 813
  • 1,185
Chris
  • 24,827
  • 43
  • 179
  • 317

4 Answers4

12

You can control the number of digits before and after the decimal point (separator). Controlling the total number of digits (before and after) is going to require some programming.

The format {0:0.00%} ought to work, giving outputs like 0.12, 1.23 and 12.34

Henk Holterman
  • 236,989
  • 28
  • 287
  • 464
5
String test = String.Format("{0:F2}", 25);

This will create 25.00

All the numeric formatting options can be found on MSDN. I use it all the time.

http://msdn.microsoft.com/en-us/library/s8s7t687.aspx

Justin
  • 3,726
  • 1
  • 17
  • 20
2
double d = 25.13645;
Console.WriteLine(d.ToString("##.00 %"));
Saar
  • 7,726
  • 5
  • 25
  • 32
1

This blog post is a great little cheat-sheet to keep handy when trying to format strings to a variety of formats.

removed

Edit

The link was removed because Google temporarily warned that the site (or related site) may have been spreading malicious software. It is now off the list an no longer reported as problematic (although it had been problematic is still reported). Google "SteveX String Formatting" you'll find the search result and you can visit it at your discretion.

Tim Cooper
  • 144,163
  • 35
  • 302
  • 261
Dave White
  • 3,417
  • 1
  • 17
  • 24
  • 2
    -1. Chrome is telling me that this site can harm my computer. http://safebrowsing.clients.google.com/safebrowsing/diagnostic?site=http://blog.stevex.net/string-formatting-in-csharp/&client=googlechrome&hl=en-US – Adam Robinson Jun 21 '10 at 14:38
  • Sorry guys. As recently as June 1, this site was not blocked and the guide was very useful for string formatting in C#. I'll try and get the content somewhere else or try to inform the owner that his site has been compromised. – Dave White Jun 21 '10 at 16:41
  • 1
    @Adam Robinson: you could (should) have removed the link. Not everybody reads the comments. – Henk Holterman Jun 21 '10 at 19:08
  • @Henk: Yeah, wasn't thinking about it when I saw it; thankfully, you were more attentive. Mea culpa! – Adam Robinson Jun 21 '10 at 19:14