CodexBloom - Programming Q&A Platform

C++20 std::format Throws std::format_error with Unexpected Locale Settings

👀 Views: 4 💬 Answers: 1 📅 Created: 2025-06-06
C++20 std::format locale C++

I'm converting an old project and I'm wondering if anyone has experience with I'm relatively new to this, so bear with me... I'm working on a project and hit a roadblock. I've been trying to use the new `std::format` function introduced in C++20 to format strings in my application. However, I'm working with a `std::format_error` whenever I try to format a number with a specific locale set. Here's a minimal example that illustrates the scenario: ```cpp #include <iostream> #include <format> #include <locale> int main() { std::locale loc("en_US.UTF-8"); std::locale::global(loc); try { std::string formatted = std::format("{:.2f}", 12345.6789); std::cout << formatted << std::endl; } catch (const std::format_error& e) { std::cout << "Format behavior: " << e.what() << std::endl; } return 0; } ``` When I run this code, I get the following output: ``` Format behavior: format specifier '.2f' requires a locale that supports the 'f' type. ``` I have verified that the `locale` is correctly set to `en_US.UTF-8`, which should support the formatting I am trying to achieve. I’ve also attempted to use other locales like `"C"`, but the behavior continues. I've confirmed that my system has the required locales installed. I am compiling this code with g++ 10.2.0 on Ubuntu 20.04. I've tried searching for similar issues but haven't found any definitive answers. Does anyone know what could be causing this behavior or how to properly format numbers with `std::format` using locales in C++20? Any guidance would be appreciated! For context: I'm using C++ on Ubuntu. What's the best practice here? I'd really appreciate any guidance on this. Any help would be greatly appreciated! Thanks for any help you can provide!