Created
September 16, 2014 13:21
-
-
Save ahills60/f8f6962b65feb18c9d9f to your computer and use it in GitHub Desktop.
Function to convert (long long) integers to strings with thousand comma separators
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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