开发者

String Format % with significant figures

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 = 12开发者_如何学Go34;
double d2 = 0.1234;

//Output of d1 -> 12
//Output of d2 -> 0.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


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


double d = 25.13645;
Console.WriteLine(d.ToString("##.00 %"));


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜