How to represent currency in C

4 Answers

0 votes
#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


*/

 



answered 10 hours ago by avibootz
edited 9 hours ago by avibootz
0 votes
/* ============================================
   Representing Currency Using Cents
   ============================================ */

#include <stdio.h>
#include <stdlib.h>

typedef long long Money;   // store cents

// Format cents as $xx.xx
void printMoney(Money cents) {
    int negative = cents < 0;
    if (negative) cents = -cents;

    long long dollars = cents / 100;
    long long remainder = cents % 100;

    if (negative) printf("-");
    printf("$%lld.%02lld", dollars, remainder);
}

int main() {
    Money priceA = 1299;   // $12.99
    Money priceB = 250;    // $2.50

    Money total = priceA + priceB;

    printf("Price A: "); printMoney(priceA); printf("\n");
    printf("Price B: "); printMoney(priceB); printf("\n");
    printf("Total  : "); printMoney(total);  printf("\n");

    return 0;
}


/*
run:

Price A: $12.99
Price B: $2.50
Total  : $15.49


*/

 



answered 10 hours ago by avibootz
0 votes
/* ============================================
   Fixed-Point Currency Representation
   ============================================ */

#include <stdio.h>

typedef struct {
    long long value;   // integer representation
    int scale;         // number of decimal digits
} Money;

// Print with correct decimal places
void printMoney(Money m) {
    long long intPart = m.value / m.scale;
    long long fracPart = m.value % m.scale;

    printf("$%lld.%0*lld", intPart, 
           (int)(fracPart < 0 ? -fracPart : fracPart), 
           (int)fracPart);
}

int main() {
    Money price = { 123456, 100 };  // 1234.56 with scale=100

    printf("Price: ");
    printMoney(price);
    printf("\n");

    return 0;
}



/*
run:

Price: $1234.00000000000000000000000000000000000000000000000000000056


*/

 



answered 10 hours ago by avibootz
0 votes
/* ============================================
   Parsing Currency Strings in C
   ============================================ */

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

long long parseMoney(const char *s) {
    long long dollars = 0, cents = 0;
    int seenDot = 0, centDigits = 0;

    while (*s) {
        if (*s == '.') {
            seenDot = 1;
        } else if (isdigit(*s)) {
            if (!seenDot) {
                dollars = dollars * 10 + (*s - '0');
            } else if (centDigits < 2) {
                cents = cents * 10 + (*s - '0');
                centDigits++;
            }
        }
        s++;
    }

    if (centDigits == 1) cents *= 10;  // "12.3" → "12.30"

    return dollars * 100 + cents;
}

int main() {
    const char *input = "12.45";
    long long cents = parseMoney(input);

    printf("Parsed cents: %lld\n", cents);  // 1245

    return 0;
}



/*
run:

Parsed cents: 1245


*/

 



answered 10 hours ago by avibootz
...