Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert spaces in a big number to make it more readable?

I came up with this, since other examples provided on stackoverflow were in C#

string number_fmt(ulong n)
{
    // cout << "(" << n << ")" << endl;
    char s[128];
    sprintf(s, "%lu", n);
    string r(s);
    reverse(r.begin(), r.end());
    int space_inserted = 0;
    size_t how_many_spaces = r.length() / 3;

    if(r.length() % 3 != 0)
        how_many_spaces += 1;

    for(int i = 1; i < how_many_spaces; ++i)
    {
        r.insert(3 * i + space_inserted, " ");
        space_inserted += 1;
    }
    reverse(r.begin(), r.end());

    return r;
}

Do you know any better solution ?

like image 603
jokoon Avatar asked Aug 31 '11 13:08

jokoon


People also ask

How do you add a space in a number in Java?

Manual Spacing For instance, to output three different integers, "i," "j" and "k," with a space between each integer, use the following code: System. out. println(i + " " + j + " " + k);

How do you write big numbers in C++?

Try digit separator: int i = 1'000'000'000; This feature is introduced since C++14. It uses single quote ( ' ) as digit separator.


1 Answers

I don't know about "better", but this version uses std::locale, etc.

#include <iostream>
#include <locale>
#include <sstream>

template<class Char>
class MyFacet : public std::numpunct<Char> {
public:
  std::string do_grouping() const { return "\3"; }
  Char do_thousands_sep() const { return ' '; }
};

std::string number_fmt(unsigned long n)
{
  std::ostringstream oss;
  oss.imbue(std::locale(oss.getloc(), new MyFacet<char>));
  oss << n;
  return oss.str();
}

int main() {
  std::cout << number_fmt(123456789) << "\n";
}


EDIT: Of course, if your final goal is to print the values on an ostream, you can skip storing them in a string altogether.
#include <iostream>
#include <locale>
#include <sstream>
#include <cwchar>

template <class Char>
class MyFacet : public std::numpunct<Char> {
public:
  std::string do_grouping() const { return "\3"; }
  Char do_thousands_sep() const { return ' '; }
};

int main(int ac, char **av) {
  using std::locale;
  using std::cout;

  // Show how it works to start with
  cout << 123456789 << "\n";

  // Switch it to spacey mode
  locale oldLoc =
    cout.imbue(locale(cout.getloc(), new MyFacet<char>));

  // How does it work now?
  cout << 456789123 << "\n";

  // You probably want to clean up after yourself
  cout.imbue(oldLoc);

  // Does it still work?
  cout << 789123456 << "\n";
}
like image 159
Robᵩ Avatar answered Oct 13 '22 00:10

Robᵩ