-1

I'm really posting cause I've had this question in the past and found it slightly hard to find an answer. Eventually I did stumble upon something but it wasn't the cleanest thing. I've eventually progressed in my coding knowledge and I was able to make a function that seems pretty clean. Posting here to share and hopefully it helps others.

Pichuu64
  • 83
  • 6
  • Looks like a duplicate of [this question](https://stackoverflow.com/questions/7276826/c-format-number-with-commas). – Nathan Pierson Jun 14 '21 at 21:27
  • What do you mean by "printing numbers with commas"? – eerorika Jun 14 '21 at 21:45
  • StackOverflow is a Q&A site. While posting your own answers is OK and [even encouraged](https://stackoverflow.com/help/self-answer), your post should be in the form of a question. – Remy Lebeau Jun 14 '21 at 23:56

1 Answers1

0

EDITS: Several Edits due to issues dealing with negative numbers, solution is really a work around but still looks pretty neat by my standars.

I'm essentially relying on the to_string function and then just adding the commas where necessary.

inline string printWithCommas(unsigned int number) {
    string temp = to_string(number);
    unsigned int numLength = temp.size();

    temp.reserve((numLength - 1) / 3 + numLength);
    for (unsigned int i = 1; i <= (numLength - 1) / 3; i++)
        temp.insert(numLength - i * 3, 1, ',');
    
    return temp;
}

For integers that can possibly be negative.

inline string printWithCommas(int number) {
    if (number < 0)
        return string("-").append(printWithCommas((unsigned int)(number*-1));
    return printWithCommas((unsigned int)number);
}

For floating point and doubles it changes only for the initialization of numLength.

inline __device__ __host__ string printWithCommas(long double number) {
    if (number < 0)
        return string("-").append(printWithCommas(number * -1));

    string temp = to_string(number);
    unsigned int numLength = temp.find('.');

    temp.reserve((numLength - 1) / 3 + numLength);
    for (unsigned int i = 1; i <= (numLength - 1) / 3; i++)
        temp.insert(numLength - i * 3, 1, ',');

    return temp;
}

On my method file I have the function overloaded for every datatype to avoid mess with implicit conversions. So like:

inline std::string printWithCommas(int number);
inline std::string printWithCommas(long int number);
inline std::string printWithCommas(long long int number);

inline std::string printWithCommas(unsigned int number);
inline std::string printWithCommas(long unsigned int number);
inline std::string printWithCommas(long long unsigned int number);

inline std::string printWithCommas(float number);
inline std::string printWithCommas(double number);
inline std::string printWithCommas(long double number);
Pichuu64
  • 83
  • 6