Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

string - Engineering notation in C#?

Is there any code out there (or a built-in function) which allows outputting a floating point number in engineering notation?

For example, 1.5e-4 would be displayed as 150μ and 5e-3 would be displayed as 5m.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This may need refactoring:

private static string ToEngineeringNotation(this double d)
{
    double exponent = Math.Log10(Math.Abs(d));
    if (Math.Abs(d) >= 1)
    {
        switch ((int)Math.Floor(exponent))
        {
            case 0: case 1: case 2:
                return d.ToString();
            case 3: case 4: case 5:
                return (d / 1e3).ToString() + "k";
            case 6: case 7: case 8:
                return (d / 1e6).ToString() + "M";
            case 9: case 10: case 11:
                return (d / 1e9).ToString() + "G";
            case 12: case 13: case 14:
                return (d / 1e12).ToString() + "T";
            case 15: case 16: case 17:
                return (d / 1e15).ToString() + "P";
            case 18: case 19: case 20:
                return (d / 1e18).ToString() + "E";
            case 21: case 22: case 23:
                return (d / 1e21).ToString() + "Z";
            default:
                return (d / 1e24).ToString() + "Y";
        }
    }
    else if (Math.Abs(d) > 0)
    {
        switch ((int)Math.Floor(exponent))
        {
            case -1: case -2: case -3:
                return (d * 1e3).ToString() + "m";
            case -4: case -5: case -6:
                return (d * 1e6).ToString() + "μ";
            case -7: case -8: case -9:
                return (d * 1e9).ToString() + "n";
            case -10: case -11: case -12:
                return (d * 1e12).ToString() + "p";
            case -13: case -14: case -15:
                return (d * 1e15).ToString() + "f";
            case -16: case -17: case -18:
                return (d * 1e15).ToString() + "a";
            case -19: case -20: case -21:
                return (d * 1e15).ToString() + "z";
            default:
                return (d * 1e15).ToString() + "y";
        }
    }
    else
    {
        return "0";
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...