c++ format number thousands separator

To format a number with thousands separators in C++, you can use the <iomanip> library along with the std::fixed and std::setprecision manipulators. Here are the steps to achieve this:

  1. Include the <iomanip> library at the beginning of your program:
#include <iomanip>
  1. Declare the number you want to format:
double number = 1234567.89;
  1. Set the precision of the output using std::setprecision:
std::cout << std::fixed << std::setprecision(2);
  • std::fixed ensures that the output is displayed with a fixed number of decimal places.
  • std::setprecision(2) sets the precision to 2 decimal places. You can change the number inside setprecision to the desired number of decimal places.

  • Print the formatted number using std::cout:

std::cout << number << std::endl;

Putting it all together, here is a complete example:

#include <iostream>
#include <iomanip>

int main() {
    double number = 1234567.89;
    std::cout << std::fixed << std::setprecision(2);
    std::cout << number << std::endl;

    return 0;
}

When you run this program, the output will be:

1,234,567.89

This is the formatted number with the thousands separator.