Alex Rivera | Logout

Formatting double as string in C#

Asked 2008-12-10T03:36:51.530
9

I have a Double which could have a value from around 0.000001 to 1,000,000,000.000

I wish to format this number as a string but conditionally depending on its size. So if it's very small I want to format it with something like:

String.Format("{0:.000000000}", number);

if it's not that small, say 0.001 then I want to use something like

String.Format("{0:.00000}", number);

and if it's over, say 1,000 then format it as:

String.Format("{0:.0}", number);

Is there a clever way to construct this format string based on the size of the value I'm going to format?

Edit
Report

1 Answer

2

Use the # character for optional positions in the string:

string.Format("{0:#,###,##0.000}", number);

I don't think you can control the number of decimal places like that as the precision of the double will likely mess things up.

To encapsulate the logic of deciding how many decimal places to output you could look at creating a custom formatter.

answered 2008-12-10T03:42:52.733

Your Answer