Skip to content

Instantly share code, notes, and snippets.

@KristofferK
Last active January 5, 2018 15:15
Show Gist options
  • Save KristofferK/e9e8c50d3de4838b5f001683437ef607 to your computer and use it in GitHub Desktop.
Save KristofferK/e9e8c50d3de4838b5f001683437ef607 to your computer and use it in GitHub Desktop.
Formatting numbers
using System;
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 string[] names = new string[] { "k", "million", "billion", "trillion", "quadrillion", "quintilion", "sextillion" };
public string Format(double d)
{
for (var i = names.Length - 1; i >= 0; i--)
{
var limit = Math.Pow(10, (i + 1) * 3);
if (d >= limit)
{
return (d / limit).ToString("f3") + " " + names[i];
}
}
return d.ToString();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment