A game framework written with osu! in mind.
1// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
2// See the LICENCE file in the repository root for full licence text.
3
4using System;
5
6namespace osu.Framework.Utils
7{
8 /// <summary>
9 /// Exposes functionality for formatting numbers.
10 /// </summary>
11 public static class NumberFormatter
12 {
13 private static readonly string[] suffixes = { "y", "z", "a", "f", "p", "n", "µ", "m", "", "k", "M", "G", "T", "P", "E", "Z", "Y" };
14
15 /// <summary>
16 /// Prints the number with at most two decimal digits, followed by a magnitude suffic (k, M, G, T, etc.) depending on the magnitude of the number. If the number is
17 /// too large or small this will print the number using scientific notation instead.
18 /// </summary>
19 /// <param name="number">The number to print.</param>
20 /// <returns>The number with at most two decimal digits, followed by a magnitude suffic (k, M, G, T, etc.) depending on the magnitude of the number. If the number is
21 /// too large or small this will print the number using scientific notation instead.</returns>
22 public static string PrintWithSiSuffix(double number)
23 {
24 // The logarithm is undefined for zero.
25 if (number == 0)
26 return "0";
27
28 var isNeg = number < 0;
29 number = Math.Abs(number);
30
31 int log1000 = (int)Math.Floor(Math.Log(number, 1000));
32 int index = log1000 + 8;
33
34 if (index >= suffixes.Length)
35 return $"{(isNeg ? "-" : "")}{number:E}";
36
37 return $"{(isNeg ? "-" : "")}{number / Math.Pow(1000, log1000):G3}{suffixes[index]}";
38 }
39 }
40}