views:

105

answers:

4

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
+3  A: 

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
+1 for being the only actually correct answer to the question.
Adam Robinson
+1  A: 
double d = 25.13645;
Console.WriteLine(d.ToString("##.00 %"));
Saar
Why the '#' in front? And '##.00' is the same as '#.00'.
Henk Holterman
A: 

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

removed

Cheers

Dave

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.

Dave White
Adam Robinson
`Warning: Visiting this site may harm your computer!`Malware???
Rippo
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
@Adam Robinson: you could (should) have removed the link. Not everybody reads the comments.
Henk Holterman
@Henk: Yeah, wasn't thinking about it when I saw it; thankfully, you were more attentive. Mea culpa!
Adam Robinson
A: 
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