String Format % with significant figures
Asked Answered
L

4

7

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
Ludicrous answered 21/6, 2010 at 14:10 Comment(1)
shouldn't you use a '.' rather than the ':' you are using. So something like : {#0.00%}Ossein
M
13

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

Meadow answered 21/6, 2010 at 14:13 Comment(1)
+1 for being the only actually correct answer to the question.Consumption
T
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

Tran answered 21/6, 2010 at 17:40 Comment(0)
P
2
double d = 25.13645;
Console.WriteLine(d.ToString("##.00 %"));
Peek answered 21/6, 2010 at 14:14 Comment(0)
B
0

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.

Beghtol answered 21/6, 2010 at 14:27 Comment(3)
-1. Chrome is telling me that this site can harm my computer. safebrowsing.clients.google.com/safebrowsing/…Consumption
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.Beghtol
@Henk: Yeah, wasn't thinking about it when I saw it; thankfully, you were more attentive. Mea culpa!Consumption

© 2022 - 2024 — McMap. All rights reserved.