Sometimes you will have to play with numbers, BIG numbers… Or teeny-tiny ones! To avoid having too many zeros you can use the SI prefixes (like metric units: mm, cm, m, km, …).
Here are the results of our code:
123,460000 -> 123,460 w (1000) 123,460000 -> 123,460 w (1024) 1.234,560000 -> 1,235 kw (1000) 1.234,560000 -> 1,206 kw (1024) 123.456,000000 -> 123,456 kw (1000) 123.456,000000 -> 120,563 kw (1024) 1.234.567,000000 -> 1,235 Mw (1000) 1.234.567,000000 -> 1,177 Mw (1024) 12.345.678,000000 -> 12,346 Mw (1000) 12.345.678,000000 -> 11,774 Mw (1024) 0,012300 -> 12,300 mw (1000) 0,012300 -> 12,595 mw (1024) 0,000012 -> 12,300 µw (1000) 0,000012 -> 12,897 µw (1024)
And here is the helper:
static void Main(string[] args) { var unit = "w"; // To denote we are measuring "wathever" foreach (var example in new[] { 123.46, 1234.56, 123456, 1234567, 12345678, 0.0123, 0.0000123 }) { foreach (var groupWeight in new[] { 1000 /* Decimal*/, 1024 /* Binary */ }) { Console.WriteLine("{0,22:#,##0.000000} -> {1,16} ({2,4})", example, Format(example, unit, groupWeight), groupWeight); } } Console.ReadLine(); } static string Format( double number, string unitSymbol, int groupWeight = 1000, string unitMultipliers = " kMGT", string unitDivider = " mµnp") { string formatted = null; var numberWeigth = (int)Math.Floor(Math.Log(number) / Math.Log(groupWeight)); Nullable<char> unitWeigthSymbol = null; if (numberWeigth > 0) { numberWeigth = Math.Min(numberWeigth, unitMultipliers.Length - 1); unitWeigthSymbol = unitMultipliers[numberWeigth]; } else { numberWeigth = -Math.Min(Math.Abs(numberWeigth), unitDivider.Length - 1); unitWeigthSymbol = unitDivider[-numberWeigth]; } number = number / Math.Pow(groupWeight, numberWeigth); formatted = string.Format("{0:0.000} {1}{2}", number, unitWeigthSymbol, unitSymbol); return (formatted); } }
Now if you need to specify the decimal separator as a dot or as a coma, please have a look at this article.
Happy coding^9 ! 😉