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

1

5

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

Echinus answered 10/8, 2011 at 13:5 Comment(3)
This is commonly called "Engineering Notation" and is also discussed in this question: https://mcmap.net/q/183515/-engineering-notation-in-c.Cephalothorax
Thanks B Pete. Had seen that post but since I'm not an engineer I started getting confused with the units, colleague had just asked about the multiples of three, not necessarily with the units in the table. Interesting post though, I might float it as an option :)Echinus
Whether you use the unit designations (m,k,...) or not, I thought that some of the methods discussed in the other question could be useful in solving the problem as you stated it.Cephalothorax
L
4

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));
}
Lacking answered 10/8, 2011 at 13:31 Comment(1)
Ah, cool! Hadn't thought to analyse the already-parsed string and manipulate it from there. Will write this into a converter and give it a go, thanks for the idea & the code :DEchinus

© 2022 - 2024 — McMap. All rights reserved.