Reputation: 144
I am using humanizr.net in a .NET project to format dates and it works really well.
Now I want to format large numbers to short - readable ones like this: 1234 -> 1.2K 50,323 -> 50.3K Just like Facebook like counts...
Is there a way to do that using Humanizer?
Upvotes: 1
Views: 1067
Reputation: 270
That's a really great solution, lucky.
I needed this also, and have just modified your solution slightly so that I can also display in 'billions' as I was getting an Out of Range exception without it. Posting here in case anyone else needs for billions.
public static string FormatLargerNumbers(double number)
{
string[] prefix = { string.Empty, "K", "M", "B" };
var absnum = Math.Abs(number);
double add;
if (absnum < 1)
{
add = (int)Math.Floor(Math.Floor(Math.Log10(absnum)) / 3);
}
else
{
add = (int)(Math.Floor(Math.Log10(absnum)) / 3);
}
var shortNumber = number / Math.Pow(10, add * 3);
return string.Format("{0}{1}", shortNumber.ToString("0.#"),
(prefix[Convert.ToInt32(add)]));
}
Upvotes: 0
Reputation: 13146
Try something like this:
public static string FormatLargerNumbers(double number)
{
string[] prefix = { string.Empty, "K", "M" };
var absnum = Math.Abs(number);
int add;
if (absnum < 1)
{
add = (int)Math.Floor(Math.Floor(Math.Log10(absnum)) / 3);
}
else
{
add = (int)(Math.Floor(Math.Log10(absnum)) / 3);
}
var shortNumber = number / Math.Pow(10, add * 3);
return string.Format("{0}{1}",shortNumber.ToString("0.#"), prefix[add]);
}
string formatted = FormatLargerNumbers(50323);
// Output : 50,3K
Upvotes: 1