-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprintf_uint_commas.c
More file actions
34 lines (21 loc) · 955 Bytes
/
printf_uint_commas.c
File metadata and controls
34 lines (21 loc) · 955 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
void printf_uint_commas(uint unsigned_integer) {
// Maximum unsigned integer value = 2,147,483,647
// Maximum digit 10 value = 2 (2,nnn,nnn,nnn)
uint digit_10_only = (unsigned_integer / (uint)1e9);
uint digits_9_to_7 = (unsigned_integer / (uint)1e6) % 1000U;
uint digits_6_to_4 = (unsigned_integer / (uint)1e3) % 1000U;
uint digits_3_to_1 = (unsigned_integer / (uint)1e0) % 1000U;
if (unsigned_integer < (uint)1e3) { // < 1,000
printf("%u",
digits_3_to_1);
} else if (unsigned_integer < (uint)1e6) { // < 1,000,000
printf("%u,%03u",
digits_6_to_4, digits_3_to_1);
} else if (unsigned_integer < (uint)1e9) { // < 1,000,000,000
printf("%u,%03u,%03u",
digits_9_to_7, digits_6_to_4, digits_3_to_1);
} else { // > 999,999,999
printf("%u,%03u,%03u,%03u",
digit_10_only, digits_9_to_7, digits_6_to_4, digits_3_to_1);
}
}