venom
venom

Reputation: 15

How to add commas to a number if it's declared as a double?

lets say I want the user to input a number and I want that number to cout with commas.

Example.

double attemptOne;

cout << "Enter a number: ";
cin >> attemptOne;  //user inputs 10000.25
cout << endl << attemptOne;  //I want to cout 10,000.25

I am new in c++ so please help me with out I am not talking about the decimal to be changed to a comma but for the program to know when the number is bigger than 999 to add commas like 1,000.25 10,000.25 100,000.25. I also do NOT want to use local

Upvotes: 1

Views: 1475

Answers (1)

Killzone Kid
Killzone Kid

Reputation: 6240

Maybe, since you need a string, you can read a string as well, and just parse it, adding commas every 3rd digit from the decimal point, or from the end if no decimal point exists:

#include <iostream>
#include <string>

int main()
{
    std::string attemptOne;
    std::cout << "Enter a number: ";
    std::cin >> attemptOne;

    size_t dec = attemptOne.rfind('.');
    if (dec == std::string::npos)
        dec = attemptOne.size();

    while (dec > 3)
        attemptOne.insert(dec -= 3, 1, ',');

    std::cout << attemptOne << std::endl;
}

Upvotes: 1

Related Questions