Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Formatting a number with a metric prefix? [duplicate]

Possible Duplicate:
Engineering notation in C#?

Whether a metric prefix is preferable to the scientific notation may be up for debate but i think it has its use-cases for physical units.

I had a look around but it seems .NET does not have anything like that built in, or am i mistaken about that? Any method of achieving that would be fine.

As a clarification: The goal is to display any given number as a floating point or integer string with a value between 1 and 999 and the respective metric prefix.

e.g.

1000 -> 1k
0.05 -> 50m

With some rounding:

1,436,963 -> 1.44M

like image 632
H.B. Avatar asked Aug 29 '12 15:08

H.B.


People also ask

What is metric prefix notation?

Metric notation uses a prefix for exponents corresponding to the traditional name or number of commas. Scientific notation uses the power of 10 to show the magnitude of a number.


1 Answers

Try this out. I haven't tested it, but it should be more or less correct.

public string ToSI(double d, string format = null)
{
    char[] incPrefixes = new[] { 'k', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y' };
    char[] decPrefixes = new[] { 'm', '\u03bc', 'n', 'p', 'f', 'a', 'z', 'y' };

    int degree = (int)Math.Floor(Math.Log10(Math.Abs(d)) / 3);
    double scaled = d * Math.Pow(1000, -degree);

    char? prefix = null;
    switch (Math.Sign(degree))
    {
        case 1:  prefix = incPrefixes[degree - 1]; break;
        case -1: prefix = decPrefixes[-degree - 1]; break;
    }

    return scaled.ToString(format) + prefix;
}
like image 71
Thom Smith Avatar answered Oct 21 '22 01:10

Thom Smith