Skip to content

Instantly share code, notes, and snippets.

@KristofferK
Last active January 5, 2018 15:32
Show Gist options
  • Save KristofferK/7cf32f21d5f0a5a97aa8843dbb78ba51 to your computer and use it in GitHub Desktop.
Save KristofferK/7cf32f21d5f0a5a97aa8843dbb78ba51 to your computer and use it in GitHub Desktop.
Formatting numbers alternative
using System;
using System.Collections.Generic;
using System.Linq;
namespace NumberFormatter
{
class Program
{
private static Formatter formatter = new Formatter();
static void Main(string[] args)
{
var numbers = new double[] { 10, 1234, 15000, 7500000, 19291921, 129312932193219, 1239812379128379281, 12389721983721983217111d };
var numbersFormatted = numbers.Select(formatter.Format).ToArray();
Console.WriteLine(String.Join("\n", numbersFormatted));
}
}
public class Formatter
{
private Dictionary<double, string> names = new Dictionary<double, string>
{
{ 1000, "k" } ,
{ 1000000, "million" },
{ 1000000000, "billion" },
{ 1000000000000, "trillion" },
{ 1000000000000000, "quadrillion" },
{ 1000000000000000000, "quintilion" },
{ 1000000000000000000000d, "sextillion" },
};
public string Format(double d)
{
var unit = names.Reverse().Where(e => d >= e.Key).FirstOrDefault();
if (string.IsNullOrWhiteSpace(unit.Value)) return d.ToString();
return (d / unit.Key).ToString("f3") + " " + unit.Value;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment