#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/*
Representing currency in C
--------------------------
Correct approach:
- Store money as integer cents (long long)
- Format for display only at the end
This avoids floating‑point rounding errors.
*/
/* Convert integer cents → formatted string with commas */
void format_money(long long cents, char *out) {
int negative = cents < 0;
if (negative) cents = -cents;
long long dollars = cents / 100;
long long frac = cents % 100;
char temp[64] = "";
sprintf(temp, "%lld", dollars);
int len = strlen(temp);
int commas = (len - 1) / 3;
int new_len = len + commas;
int i = len - 1;
int j = new_len - 1;
int digit_count = 0;
while (i >= 0) {
out[j--] = temp[i--];
digit_count++;
if (digit_count == 3 && i >= 0) {
out[j--] = ',';
digit_count = 0;
}
}
out[new_len] = '\0';
char fracbuf[8];
sprintf(fracbuf, ".%02lld", frac);
if (negative) {
char final[64];
sprintf(final, "-%s%s", out, fracbuf);
strcpy(out, final);
} else {
strcat(out, fracbuf);
}
}
/* Cost of pizzas (integer cents) */
long long pizzaCostExample() {
long long pizzas = 2000000; // 2,000,000 pizzas
long long priceEach = 1200; // $12.00 → 1200 cents
return pizzas * priceEach;
}
/* Cost of milkshakes (integer cents) */
long long milkshakeCostExample() {
long long milkshakes = 3;
long long priceEach = 375; // $3.75 → 375 cents
return milkshakes * priceEach;
}
/* Apply tax rate (integer math, safe) */
long long applyTax(long long amount, double taxRate) {
// taxRate is percent (e.g., 16.25)
double multiplier = 1.0 + taxRate / 100.0;
long long result = (long long)(amount * multiplier + 0.5); // round safely
return result;
}
int main() {
long long pizzaTotal = pizzaCostExample();
long long milkshakeTotal = milkshakeCostExample();
long long pizzaWithTax = applyTax(pizzaTotal, 16.25);
char buf1[64] = "", buf2[64] = "", buf3[64] = "";
format_money(pizzaTotal, buf1);
format_money(milkshakeTotal, buf2);
format_money(pizzaWithTax, buf3);
printf("Cost of 2,000,000 pizzas at $12 each: $%s\n", buf1);
printf("Cost of 3 milkshakes at $3.75 each: $%s\n", buf2);
printf("Pizza total with 16.25%% tax: $%s\n", buf3);
return 0;
}
/*
run:
Cost of 2,000,000 pizzas at $12 each: $24,000,000.00
Cost of 3 milkshakes at $3.75 each: $11.25
Pizza total with 16.25% tax: $27,900,000.00
*/