#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
*/