6

Is it possible to format number with thousands separator using fmt?

e.g. something like this:

int count = 10000;
fmt::print("{:10}\n", count);

update

I am researching fmt, so I am looking for solution that works with fmt library only, without modify locale in any way.

Nick
  • 9,962
  • 4
  • 42
  • 80
  • 1
    `std::format` is proposed for C++20 – Michael Chourdakis Nov 19 '19 at 16:13
  • 1
    See [Thousands separator in C++](https://stackoverflow.com/a/4167029/5763413) – blackbrandt Nov 19 '19 at 16:22
  • Does this answer your question? [c++: Format number with commas?](https://stackoverflow.com/questions/7276826/c-format-number-with-commas) – phuclv Nov 19 '19 at 16:43
  • [Print integer with thousands and millions separator](https://stackoverflow.com/q/17530408/995714), [How to format a number with thousands separator in C/C++](https://stackoverflow.com/q/43482488/995714) – phuclv Nov 19 '19 at 16:44
  • 1
    all those proposed answers have nothing to do with fmt library. – Nick Nov 19 '19 at 16:47

2 Answers2

4

I found the answer online in Russian forum:

int count = 10000;
fmt::print("{:10L}\n", count);

This prints:

10,000

The thousands separator is locale depended and if you want to change it to something else, only then you need to "tinker" with locale classes.

vitaut
  • 49,672
  • 25
  • 199
  • 336
Nick
  • 9,962
  • 4
  • 42
  • 80
2

According to the fmt API reference:

Use the 'L' format specifier to insert the appropriate number separator characters from the locale. Note that all formatting is locale-independent by default.

#include <fmt/core.h>
#include <locale>

int main() {
  std::locale::global(std::locale("es_CO.UTF-8"));
  auto s = fmt::format("{:L}", 1'000'000);  // s == "1.000.000"
  fmt::print("{}\n", s);                    // "1.000.000"
  return 0;
}
Lejuanjowski
  • 139
  • 1
  • 2
  • 6