How to represent currency in C++

3 Answers

0 votes
#include <iostream>
#include <iomanip>
#include <sstream>
#include <string>
#include <cmath> // std::llround

/*
    C++ Currency Representation
    ------------------------------------
    - Store money as integer cents (std::int64_t)
    - Provide formatting via a Money class
    - Avoid floating-point errors entirely
*/

class Money {
public:
    std::int64_t cents;   // always store integer cents

    Money(std::int64_t c = 0) : cents(c) {}

    // Construct from dollars (double) safely
    static Money fromDouble(double amount) {
        return Money(static_cast<std::int64_t>(std::llround(amount * 100)));
    }

    // Convert to formatted string with commas
    std::string str() const {
        std::ostringstream oss;

        std::int64_t absCents = std::llabs(cents);
        std::int64_t dollars = absCents / 100;
        std::int64_t frac = absCents % 100;

        // Format dollars with commas
        std::string d = std::to_string(dollars);
        std::string withCommas;

        int count = 0;
        for (int i = d.size() - 1; i >= 0; --i) {
            withCommas.push_back(d[i]);
            if (++count == 3 && i > 0) {
                withCommas.push_back(',');
                count = 0;
            }
        }
        std::reverse(withCommas.begin(), withCommas.end());

        if (cents < 0)
            oss << "-";

        oss << withCommas << "." << std::setw(2) << std::setfill('0') << frac;
        
        return oss.str();
    }

    // Arithmetic
    Money operator+(const Money& other) const { return Money(cents + other.cents); }
    Money operator*(std::int64_t n) const { return Money(cents * n); }
};

// Apply tax rate (percentage)
Money applyTax(const Money& amount, double taxRate) {
    double multiplier = 1.0 + taxRate / 100.0;
    
    return Money::fromDouble(amount.cents / 100.0 * multiplier);
}

// Example calculations
Money pizzaCostExample() {
    std::int64_t pizzas = 2'000'000;
    Money priceEach = Money::fromDouble(12.00);
    
    return priceEach * pizzas;
}

Money milkshakeCostExample() {
    std::int64_t milkshakes = 3;
    Money priceEach = Money::fromDouble(3.75);
    
    return priceEach * milkshakes;
}

int main() {
    Money pizzaTotal = pizzaCostExample();
    Money milkshakeTotal = milkshakeCostExample();
    Money pizzaWithTax = applyTax(pizzaTotal, 16.25);

    std::cout << "Cost of 2,000,000 pizzas at $12 each: $" 
              << pizzaTotal.str() << "\n";

    std::cout << "Cost of 3 milkshakes at $3.75 each: $" 
              << milkshakeTotal.str() << "\n";

    std::cout << "Pizza total with 16.25% tax: $" 
              << pizzaWithTax.str() << "\n";
}



/*
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 13 hours ago by avibootz
edited 9 hours ago by avibootz
0 votes
// ===============================
// Integer Currency Type
// ===============================

#include <iostream>
#include <cstdint>
#include <iomanip>

// Convert cents → formatted string
std::string formatMoney(int64_t cents) {
    bool negative = cents < 0;
    cents = std::llabs(cents);

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

    std::ostringstream oss;
    if (negative) oss << "-";
    oss << "$" << dollars << "." << std::setw(2) << std::setfill('0') << remainder;
    return oss.str();
}

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

    int64_t total = priceA + priceB;  // exact integer math

    std::cout << "Price A: " << formatMoney(priceA) << "\n";
    std::cout << "Price B: " << formatMoney(priceB) << "\n";
    std::cout << "Total : " << formatMoney(total)  << "\n";
}



/*
run:

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

*/

 



answered 10 hours ago by avibootz
edited 9 hours ago by avibootz
0 votes
// ===============================================
// Formatting Currency with std::put_money
// ===============================================

#include <iostream>
#include <iomanip>
#include <locale>

int main() {
    long double amount = 1234.56L;

    // Use US locale
    std::cout.imbue(std::locale("en_US.UTF-8"));
    std::cout << "US Format: " << std::showbase
              << std::put_money(amount * 100) << "\n";

    // Use Japanese locale
    // Safe locale setup
    try {
    std::locale jp("ja_JP.UTF-8");
        std::cout.imbue(jp);
    } catch (const std::runtime_error& e) {
        std::cerr << "Locale not installed: ja_JP.UTF-8\n";
    }
    std::cout << "Japan Format: " << std::showbase
              << std::put_money(amount * 100) << "\n";

    return 0;
}



/*
run:

US Format: $1,234.56
Locale not installed: ja_JP.UTF-8
Japan Format: $1,234.56

*/

 



answered 10 hours ago by avibootz
...