This repository has been archived on 2026-07-19. You can view files and clone it, but you cannot make any changes to it's state, such as pushing and creating new issues, pull requests or comments.
acquire-core-migration/legacy/app/common/util_amount.c

61 lines
1.8 KiB
C

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define AMOUNT_BUF_SIZE 64
typedef struct {
long long units;
int cents;
char currency[4];
} amount_t;
int amount_parse(const char* str, amount_t* out) {
if (!str || !out) return -1;
long long units = 0;
int cents = 0;
char currency[4] = "KRW";
const char* p = str;
while (*p && !isdigit(*p) && *p != '.' && *p != '-') p++;
if (sscanf(p, "%lld.%2d", &units, &cents) >= 1) {
out->units = units;
out->cents = cents;
strcpy(out->currency, currency);
return 0;
}
return -1;
}
int amount_format(const amount_t* a, char* buf, size_t len) {
if (!a || !buf) return -1;
return snprintf(buf, len, "%s %lld.%02d", a->currency, a->units, a->cents);
}
int amount_add(const amount_t* a, const amount_t* b, amount_t* out) {
if (!a || !b || !out) return -1;
long long total_cents = a->units * 100 + a->cents + b->units * 100 + b->cents;
out->units = total_cents / 100;
out->cents = (int)(total_cents % 100);
strcpy(out->currency, a->currency);
return 0;
}
int amount_subtract(const amount_t* a, const amount_t* b, amount_t* out) {
if (!a || !b || !out) return -1;
long long total_cents = (a->units * 100 + a->cents) - (b->units * 100 + b->cents);
out->units = total_cents / 100;
out->cents = (int)(total_cents % 100);
if (total_cents < 0) out->cents = -out->cents;
strcpy(out->currency, a->currency);
return 0;
}
int amount_multiply(const amount_t* a, int factor, amount_t* out) {
if (!a || !out) return -1;
long long total_cents = (a->units * 100 + a->cents) * factor;
out->units = total_cents / 100;
out->cents = (int)(total_cents % 100);
strcpy(out->currency, a->currency);
return 0;
}