Home > Enterprise >  How can I delete decimal points from a 'double' type to later be displayed as a currency?
How can I delete decimal points from a 'double' type to later be displayed as a currency?

Time:01-23

I am currently building a mock banking app that can display the history of transactions on an account.

Part of a transaction is, naturally, the amount.

Amounts are stored as doubles in my program which leads to many of them being displayed with way too many decimal points (for example £500.000000 instead of £500.00).

When forming a transaction, the amount is simply converted to a string alongside timestamps and transaction types.

I need a way so that the double can be stored without the extra decimal places. It doesn't matter if it is converted to two decimal places before or after becoming a string.

I cannot use setprecision(2) here because I am not writing out the transaction to the console yet.

Transaction::Transaction(string desc, string timestamp, double value) {

    this->desc = desc;
    this->timestamp = timestamp;
    this->value = value;
};

string Transaction::toString() {
fullString = "-- "   desc   ": -\x9c"   to_string(value)   " on "   timestamp;
}

CodePudding user response:

I cannot use setprecision(2) here because I am not writing out the transaction to the console yet.

Yes you can use it. Just use std::ostringstream:

std::string Transaction::toString() {
    std::ostringstream fullString;
    fullstring << "-- " << desc << ": -\x9c" << std::setprecision(2) << value << " on " << timestamp;
    return fullString.str();
}

If you use C 20 or later you can use std::format

CodePudding user response:

You may use this helper function:

#include <sstream>
#include <iomanip>

std::string value2string(double value)
{
  std::ostringstream out;
  out << std::fixed << std::setprecision(2) << value;
  return out.str();
}

string Transaction::toString() {
fullString = "-- "   desc   ": -\x9c"   value2string(value)   " on "   timestamp;
}
  •  Tags:  
  • Related