75 lines
1.9 KiB
C
75 lines
1.9 KiB
C
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
#include <string.h>
|
|
#include <math.h>
|
|
|
|
typedef struct {
|
|
long long cents;
|
|
} Amount;
|
|
|
|
Amount* amount_create(long long cents) {
|
|
Amount* a = (Amount*)malloc(sizeof(Amount));
|
|
a->cents = cents;
|
|
return a;
|
|
}
|
|
|
|
Amount* amount_from_string(const char* str) {
|
|
long long cents = 0;
|
|
int decimal_pos = -1;
|
|
int len = strlen(str);
|
|
for (int i = 0; i < len; i++) {
|
|
if (str[i] >= '0' && str[i] <= '9') {
|
|
cents = cents * 10 + (str[i] - '0');
|
|
if (decimal_pos >= 0) decimal_pos++;
|
|
} else if (str[i] == '.') {
|
|
decimal_pos = 0;
|
|
}
|
|
}
|
|
while (decimal_pos < 2) {
|
|
cents *= 10;
|
|
decimal_pos++;
|
|
}
|
|
Amount* a = (Amount*)malloc(sizeof(Amount));
|
|
a->cents = cents;
|
|
return a;
|
|
}
|
|
|
|
char* amount_to_string(Amount* a) {
|
|
char* buf = (char*)malloc(32);
|
|
long long abs_cents = a->cents >= 0 ? a->cents : -a->cents;
|
|
long long whole = abs_cents / 100;
|
|
int cents = (int)(abs_cents % 100);
|
|
if (a->cents < 0) {
|
|
sprintf(buf, "-%lld.%02d", whole, cents);
|
|
} else {
|
|
sprintf(buf, "%lld.%02d", whole, cents);
|
|
}
|
|
return buf;
|
|
}
|
|
|
|
Amount* amount_add(Amount* a, Amount* b) {
|
|
Amount* result = (Amount*)malloc(sizeof(Amount));
|
|
result->cents = a->cents + b->cents;
|
|
return result;
|
|
}
|
|
|
|
Amount* amount_subtract(Amount* a, Amount* b) {
|
|
Amount* result = (Amount*)malloc(sizeof(Amount));
|
|
result->cents = a->cents - b->cents;
|
|
return result;
|
|
}
|
|
|
|
Amount* amount_multiply(Amount* a, double factor) {
|
|
Amount* result = (Amount*)malloc(sizeof(Amount));
|
|
result->cents = (long long)(a->cents * factor);
|
|
return result;
|
|
}
|
|
|
|
int amount_compare(Amount* a, Amount* b) {
|
|
if (a->cents > b->cents) return 1;
|
|
if (a->cents < b->cents) return -1;
|
|
return 0;
|
|
}
|
|
|
|
long long amount_to_cents(Amount* a) { return a->cents; }
|
|
void amount_free(Amount* a) { free(a); }
|