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

2

7

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.

Dialyser answered 19/11, 2019 at 16:10 Comment(5)
std::format is proposed for C++20Febrific
See Thousands separator in C++Deoxyribonuclease
Does this answer your question? c++: Format number with commas?Dialysis
Print integer with thousands and millions separator, How to format a number with thousands separator in C/C++Dialysis
all those proposed answers have nothing to do with fmt library.Dialyser
D
6

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.

Dialyser answered 19/11, 2019 at 17:10 Comment(0)
K
5

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;
}
Karinekariotta answered 2/7, 2021 at 14:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.