Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Engineering notation in C#?

Tags:

string

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.

like image 471
Nick Avatar asked Apr 30 '09 17:04

Nick


People also ask

How do you write exponential notation in C?

To express a number in exponential notation, write it in the form: c × 10n, where c is a number between 1 and 10 (e.g. 1, 2.5, 6.3, 9.8) and n is an integer (e.g. 1, -3, 6, -2).


2 Answers

Here is another version that handles negative and without rounding

public static string ToEngineering(this double value)
{
    var absValue = Math.Abs(value);
    var exp = absValue < 0.001 ? 0 : (int)(Math.Floor(Math.Log10(absValue) / 3.0) * 3.0);
    var newValue = value * Math.Pow(10.0, -exp);
    return $"{newValue}e{exp}";
}
like image 79
Alex Kravchenko Avatar answered Oct 25 '22 05:10

Alex Kravchenko


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";
    }
}
like image 23
Patrick McDonald Avatar answered Oct 25 '22 05:10

Patrick McDonald