Skip to content

Commit 7d96028

Browse files
Update cstring.c
1 parent a9bbc9e commit 7d96028

File tree

1 file changed

+82
-0
lines changed

1 file changed

+82
-0
lines changed

code/logic/cstring.c

Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -162,6 +162,88 @@ int fossil_io_cstring_string_to_money(const char *input, double *amount) {
162162
return 0;
163163
}
164164

165+
int fossil_io_cstring_money_to_string_currency(double amount, char *output, size_t size, const char *currency) {
166+
if (!output || size == 0) return -1;
167+
if (!currency) currency = "$";
168+
169+
amount = round(amount * 100.0) / 100.0; // Round to 2 decimals
170+
171+
char temp[64];
172+
int written = snprintf(temp, sizeof(temp), "%.2f", fabs(amount));
173+
if (written < 0 || written >= (int)sizeof(temp)) return -1;
174+
175+
// Replace decimal point with '.'
176+
char *dot = strchr(temp, '.');
177+
int int_len = dot ? (int)(dot - temp) : (int)strlen(temp);
178+
int commas = (int_len - 1) / 3;
179+
int total_len = int_len + commas + (dot ? strlen(dot) : 0);
180+
181+
if ((size_t)(total_len + strlen(currency) + 2) > size) return -1;
182+
183+
char formatted[128];
184+
int fpos = 0;
185+
186+
if (amount < 0) formatted[fpos++] = '-';
187+
strcpy(&formatted[fpos], currency);
188+
fpos += strlen(currency);
189+
190+
int leading = int_len % 3;
191+
if (leading == 0) leading = 3;
192+
193+
for (int i = 0; i < int_len; i++) {
194+
formatted[fpos++] = temp[i];
195+
if ((i + 1) % leading == 0 && (i + 1) < int_len) {
196+
formatted[fpos++] = ',';
197+
leading = 3;
198+
}
199+
}
200+
201+
if (dot) {
202+
strcpy(&formatted[fpos], dot);
203+
fpos += strlen(dot);
204+
}
205+
206+
formatted[fpos] = '\0';
207+
strncpy(output, formatted, size - 1);
208+
output[size - 1] = '\0';
209+
210+
return 0;
211+
}
212+
213+
int fossil_io_cstring_string_to_money_currency(const char *input, double *amount) {
214+
if (!input || !amount) return -1;
215+
216+
char buffer[128];
217+
size_t j = 0;
218+
int negative = 0;
219+
220+
while (isspace((unsigned char)*input)) input++;
221+
222+
if (*input == '(') {
223+
negative = 1;
224+
input++;
225+
}
226+
227+
if (!isdigit((unsigned char)*input) && *input != '-' && *input != '.') {
228+
// Skip currency symbol
229+
input++;
230+
}
231+
232+
for (size_t i = 0; input[i] && j < sizeof(buffer) - 1; i++) {
233+
if (isdigit((unsigned char)input[i]) || input[i] == '.') {
234+
buffer[j++] = input[i];
235+
}
236+
}
237+
buffer[j] = '\0';
238+
239+
if (j == 0) return -1;
240+
241+
*amount = atof(buffer);
242+
if (negative || strchr(input, '-')) *amount = -*amount;
243+
244+
return 0;
245+
}
246+
165247
// ---------------- Tokenizer ----------------
166248
cstring fossil_io_cstring_token(cstring str, ccstring delim, cstring *saveptr) {
167249
if (!saveptr || (!str && !*saveptr)) return NULL;

0 commit comments

Comments
 (0)