Skip to content

Instantly share code, notes, and snippets.

@ahills60
Created September 16, 2014 13:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ahills60/f8f6962b65feb18c9d9f to your computer and use it in GitHub Desktop.
Save ahills60/f8f6962b65feb18c9d9f to your computer and use it in GitHub Desktop.
Function to convert (long long) integers to strings with thousand comma separators
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
char *PrettyNumbers(long long int inputBytes)
{
double tempVar = log10((double) inputBytes);
int noElements = (int) floor(tempVar / 3.0), n, remn = (int) (tempVar + 1) % 3;
char *output, tempString[4];
if (remn == 0)
remn = 3;
output = malloc(sizeof(char) * ((int) ceil(tempVar) + 1 + noElements));
memset(output, 0, (int) floor(tempVar) + 2);
for (n = noElements - 1; n >= 0; n--)
{
sprintf(tempString, ",%03i", (long long int) floor((double) inputBytes / pow(1000.0, n)) % 1000);
memcpy(&output[remn + 4 * (noElements - n - 1)], &tempString[0], 4);
}
sprintf(tempString, "%3i", (int) floor((double) inputBytes / pow(1000.0, noElements)) % 1000);
memcpy(&output[0], &tempString[3 - remn], remn);
return output;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment