Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Format C# Double to Scientfic Notation in powers with multiples of three

I'm trying to format some large numbers in scientific format, but I need the power in multiples of three. Is there a recommended way to do this?

I have a range of numbers in a table and instead of true scientific format (with a single digit before the decimal point) I'm happy to have that change in order to have a power with a multiple of three, for example:

3.123e+003
19.523e+003

Rather than:

3.123e+003
1.952e+004

Having all the powers as multiples of three makes my table easier to scan, I believe.

Thanks in advance

like image 663
Marc Avatar asked Oct 11 '22 07:10

Marc


1 Answers

I think you need to write your own function. At first you can get the scientific representation of the number with the precision two digits larger than you need. Then you should parse resulting string to get floating-point coefficient and 10's power index as numbers of type decimal. After that you analyse the remainder of division index by 3 and change the numbers in the appropriate way. Finally you generate output string.

static string Scientific3(double value, int precision)
{
    string fstr1 = "{0:E" + (precision+2).ToString() + "}";
    string step1 = string.Format(fstr1, value);
    int index1 = step1.ToLower().IndexOf('e');
    if (index1 < 0 || index1 == step1.Length - 1)
        throw new Exception();
    decimal coeff = Convert.ToDecimal(step1.Substring(0, index1));
    int index = Convert.ToInt32(step1.Substring(index1 + 1));
    while(index%3!=0)
    {
        index--;
        coeff *= 10;
    }
    string fstr2 = "{0:F" + precision.ToString() + "}E{1}{2:D3}";
    return string.Format(fstr2, coeff, ((index < 0) ? "-" : "+"), Math.Abs(index));
}
like image 175
Win32.Neshto Avatar answered Oct 18 '22 07:10

Win32.Neshto