I trying to create a program that deals with money, and have it all figured out except one portion...I can't get all the decimals to have a monetary look, meaning only two decimal places. I know I can setprecision(2), and that would work for most numbers, but what if the number are mixed in their length?

Example of what I'm getting:
$12.501
$1254.0
$124.15
$10321
$1.1254

Is it possible to have them all round out to only two decimal places?

Recommended Answers

All 3 Replies

Are you doing something like the following? It works OK on my end for simple currency:

#include <iostream>
#include <iomanip>

int main()
{
    double values[] =
    {
        12.501,
        1254.0,
        124.15,
        10321,
        1.1256
    };
    const int sz = sizeof values / sizeof *values;

    std::cout.imbue(std::locale(""));

    for (int x = 0; x < sz; ++x)
    {
        std::cout << std::fixed << std::setprecision(2)
                  << '$' << values[x] << '\n';
    }
}

>>Is it possible to have them all round out to only two decimal places?

First you have to decide if :

1) You want to output up to 2 decimal
2) You want the actual value of the decimal to be 2 decimal places long.

Just add this to your coding before your variables:

cout.precision(3);
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.