I would like to take a decimal or non-decimal value and store it as a string with exactly 2 decimal places in C++. I want to do this to show it as a monetary value, so it is always $10.50 or $10.00 rather than $10.5 or $10.
I don't just want to print this, I want to store it, so I don't believe setprecision
will work here. I'm doing this in a Qt application, so if there is a way to do it using Qt I can use that as well.
For example:
int cents = 1000;
std::string dollars; //should get value from cents formatted to 10.00
UPDATE: It seems I don't have the vocabulary yet as I am just beginning to learn C++ to articulate what I am trying to do. Here is what I want to do using Python:
str_money = '$ {:.2f}'.format(num)
In this example, num can be a decimal or not (10 or 10.5 for example) and str_money is a variable that is assigned the value of num as a decimal with exactly 2 numbers after the decimal (in this example, str_money would become 10.00 or 10.50). I want it to store this in a string variable, and I don't need it to store the '$' with the value.
Can I do this in C++?