Skip to content

Instantly share code, notes, and snippets.

@aloisdg
Created September 13, 2015 16:03
Show Gist options
  • Save aloisdg/8254e66b5b96ed7b8ce8 to your computer and use it in GitHub Desktop.
Save aloisdg/8254e66b5b96ed7b8ce8 to your computer and use it in GitHub Desktop.
using System;
using System.Globalization;
using System.Linq;
public class Program
{
/// <see cref="https://en.wikipedia.org/wiki/Metric_prefix#List_of_SI_prefixes" />
public static void Main()
{
try
{
for (int i = 0; i < 27; i++) // see 43
{
var d = HumanizeBigNumber(Math.Pow(10, i));
Console.WriteLine(d.PadRight(10) + DehumanizeBigNumber(d));
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
private static string HumanizeBigNumber(double bigNumber)
{
const string symbols = "kMGTPEZY";
var numbers = bigNumber
.ToString("0.##################E+0", CultureInfo.InvariantCulture) // scientific notation
.Split(new[] { 'E', '+' }, StringSplitOptions.RemoveEmptyEntries) // split {significand}, {exponent}
.Select(Double.Parse).ToArray();
var number = numbers[0] * Math.Pow(10, numbers[1] % 3); // significand > 0 && < 1000
var i = (numbers[1] / 3) - 1; // index to select in chars
if (i >= symbols.Length)
throw new ArgumentOutOfRangeException("bigNumber"); // 1.0E+27 is the max. Check before to optimize
var letter = i >= 0 ? symbols[(int)i].ToString() : String.Empty; // get valid letter
return number + letter;
}
private static double DehumanizeBigNumber(string humanizeBigNumber)
{
const string symbols = "kMGTPEZY";
var letter = Char.IsLetter(humanizeBigNumber.Last()) ? humanizeBigNumber.Last().ToString() : String.Empty;
return String.IsNullOrEmpty(letter)
? Double.Parse(humanizeBigNumber)
: (Double.Parse(humanizeBigNumber.Remove(humanizeBigNumber.Length - 1))
* Math.Pow(10, 3 + symbols.IndexOf(letter, StringComparison.Ordinal) * 3));
}
}
@aloisdg
Copy link
Author

aloisdg commented Sep 13, 2015

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment