Formatting a number with a metric prefix? [duplica

2020-06-01 08:48发布

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

3条回答
▲ chillily
2楼-- · 2020-06-01 09:23

Create an extension method for each numeric type. You would call ToStringMetric() for you custom formatting.

public static class Int32Extensions
{
        public static string ToStringMetric(this Int32 x) { return (x / 1000).ToString() + " K"; }
}
查看更多
Viruses.
3楼-- · 2020-06-01 09:31

According to these SO Articles and to my own research, there is no native way to format numbers in metric units. You will need to write your own methods to parse the units and append the relevant metric measurement, such as for instance an expanded example of this interface tutorial at MSDN. You can also try to find a metric units coding library to use for development.

查看更多
对你真心纯属浪费
4楼-- · 2020-06-01 09:34

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;
}
查看更多
登录 后发表回答