Engineering notation in C#?

前端 未结 9 2173
离开以前
离开以前 2020-12-03 17:44

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

9条回答
  •  时光取名叫无心
    2020-12-03 18:27

    ICustomFormmatter using a private dictionary for the symbols.

    class EngNotationFormatter : IFormatProvider, ICustomFormatter
    {
        private readonly Dictionary notationSymbols = new Dictionary
        {
            {double.NegativeInfinity, ""}, //Handles when value is 0
            {-24, "y"},
            {-21, "z"},
            {-18, "a"},
            {-15, "f"},
            {-12, "p"},
            {-9, "n"},
            {-6, "μ"},
            {-3, "m"},
            {0, ""},
            {3, "k"},
            {6, "M"},
            {9, "G"},
            {12, "T"},
            {15, "P"},
            {18, "E"},
            {21, "Z"},
            {24, "Y"},
        };
    
        public string Format(string format, object arg, IFormatProvider formatProvider)
        {
            double value = Convert.ToDouble(arg);
            double engExponent = Math.Floor(Math.Log10(value) / 3) * 3;
    
            return (value * Math.Pow(10, (int)-engExponent)) + notationSymbols[engExponent];
        }
    
        public object GetFormat(Type formatType)
        {
            if (formatType == typeof(ICustomFormatter))
                return this;
            else
                return null;
        }
    }
    

    Example use

    (0.00005678).ToString(new EngNotationFormatter()); //56.78μ
    (0.1234).ToString(new EngNotationFormatter());     //123.4m
    (0).ToString(new EngNotationFormatter());          //0
    (1300).ToString(new EngNotationFormatter());       //1.3k
    (19000).ToString(new EngNotationFormatter());      //19k
    

提交回复
热议问题