Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Formatting double as string in C#

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?

like image 203
Guy Avatar asked Dec 10 '08 03:12

Guy


1 Answers

Use Math.Log10 of the absolute value of the double to figure out how many 0's you need either left (if positive) or right (if negative) of the decimal place. Choose the format string based on this value. You'll need handle zero values separately.

string s;
double epislon = 0.0000001; // or however near zero you want to consider as zero
if (Math.Abs(value) < epislon) {
    int digits = Math.Log10( Math.Abs( value ));
    // if (digits >= 0) ++digits; // if you care about the exact number
    if (digits < -5) {
       s = string.Format( "{0:0.000000000}", value );
    }
    else if (digits < 0) {
       s = string.Format( "{0:0.00000})", value );
    }
    else {
       s = string.Format( "{0:#,###,###,##0.000}", value );
    }
}
else {
    s = "0";
}

Or construct it dynamically based on the number of digits.

like image 118
tvanfosson Avatar answered Oct 18 '22 00:10

tvanfosson