Phil Brockwell
Phil Brockwell

Reputation: 465

Output as currency in C++

I have a simple C++ command line program where I am taking an input from the user then displaying it as a price, with a currency symbol, commas separating each set of 3 values, a decimal point, and two decimal places which will display even if they are zero.

Example of what I am trying to achieve:

100 => £100.00
101.1 => £101.10
100000 => £100,000.00

Here is my method so far:

void output_price() {
    int price;

    cout << "Enter a price" << endl;
    cin >> price;
    string num_with_commas = to_string(price);
    int insert_position = num_with_commas.length() - 3;
    while (insert_position > 0) {
        num_with_commas.insert(insert_position, ",");
        insert_position -= 3;
    }

    cout << "The Price is: £" << num_with_commas << endl;
}

This is partly working but doesn't show the decimal point/places.

1000 => £1000

If I change price to a float or double it gives me this:

1000 => £10,00.,000,000

I am trying to keep things simple and avoid creating a currency class, however not sure if this is possible in C++.

Any help appreciated.

Upvotes: 1

Views: 2595

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726499

The logical error is here:

int insert_position = num_with_commas.length() - 3;

The original value of num_with_commas could have any number of digits after the dot, including no dot at all; moreover, you have no control over it, because the format applied by std::to_string is fixed.

If you would like to continue using std::to_string, you need to make a few changes:

  • Locate the position of the dot '.' character.
  • If the dot is there, and the number of characters after it is less than 2, keep appending zeros "0" until dot '.' is the third character from the back
  • If the dot is there, and there are more than two characters after it, remove the tail of the string so that there are exactly two characters after the dot
  • If the dot is not there, append ".00" to string

The rest of your algorithm that inserts dots will work fine.

Upvotes: 1

Related Questions