Formatting a number with a metric prefix? [duplicate]

浪尽此生 提交于 2019-12-03 05:36:57
Thom Smith

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;
}
JackOrangeLantern

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.

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"; }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!