Last active
September 6, 2024 08:11
-
-
Save thaolt/616a30d27e6e761527f2a3877304b91c to your computer and use it in GitHub Desktop.
Number format for thousand separators in C programming language
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 <stdint.h> | |
/** | |
* @brief Format a number in the format of 123.456.789 | |
* | |
* @param[out] outbuf output buffer | |
* @param[in/out] outcaplen output buffer capacity + return length | |
* @param[in] num number to format | |
* @param[in] thousep thousands separator | |
* | |
* @return error code (zero if success, -1 otherwise) | |
**/ | |
int number_format(char *outbuf, size_t *outcaplen, uint64_t num, char thousep) | |
{ | |
uint16_t t[10] = {0}; | |
uint8_t l = 0; | |
while (num / 1000 != 0) { | |
t[l++] = num % 1000; | |
num /= 1000; | |
} | |
t[l++] = num % 1000; | |
if (*outcaplen < l * 4) { | |
*outcaplen = 0; | |
return -1; | |
} | |
sprintf(outbuf, "%d", t[l---1]); | |
uint8_t fo = strlen(outbuf); | |
if (l > 0) { | |
outbuf[fo++] = thousep; | |
outbuf[fo] = 0; | |
uint8_t j = 0; | |
if (l > 1) { | |
for (int i = l - 1; i > 0; --i) { | |
sprintf(outbuf+fo+(j++*4), "%0*d%c", 3, t[i], thousep); | |
} | |
} | |
sprintf(outbuf+fo+j*4, "%0*d", 3, t[0]); | |
} | |
*outcaplen = strlen(outbuf); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
you need to include the following :
#include <string.h>
if you leave it out, you will get a warning!