我目前正在構建一個模擬銀行應用程式,可以顯示帳戶交易的歷史記錄。
交易的一部分自然是金額。
金額在我的程式中存盤為雙精度數,這導致其中許多顯示的小數點太多(例如 500.000000 英鎊而不是 500.00 英鎊)。
形成交易時,金額與時間戳和交易型別一起簡單地轉換為字串。
我需要一種方法,以便可以在沒有額外小數位的情況下存盤雙精度。在成為字串之前或之后轉換為小數點后兩位都沒有關系。
我不能在這里使用 setprecision(2) 因為我還沒有將事務寫到控制臺。
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;
}
uj5u.com熱心網友回復:
我不能在這里使用 setprecision(2) 因為我還沒有將事務寫到控制臺。
是的,你可以使用它。只需使用std::ostringstream:
std::string Transaction::toString() {
std::ostringstream fullString;
fullstring << "-- " << desc << ": -\x9c" << std::setprecision(2) << value << " on " << timestamp;
return fullString.str();
}
如果您使用 C 20 或更高版本,您可以使用 std::format
uj5u.com熱心網友回復:
你可以使用這個輔助函式:
#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;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/419280.html
標籤:
上一篇:超過1000每500增加1
