Home > Backend Development > C++ > body text

How to Format Numbers with Commas in C Using std::locale?

Barbara Streisand
Release: 2024-10-27 00:19:31
Original
922 people have browsed it

How to Format Numbers with Commas in C   Using std::locale?

Formatting Numbers with Commas in C

In C , the std::locale class provides a locale-dependent way to format numbers with commas.

std::locale with std::stringstream

To format a number as a string with commas, you can use std::locale with std::stringstream as follows:

<code class="cpp">#include <iomanip>
#include <locale>

template<class T>
std::string FormatWithCommas(const T& value) {
  std::stringstream ss;
  ss.imbue(std::locale(""));  // Use the system's locale
  ss << std::fixed << value;
  return ss.str();
}</code>
Copy after login

Example Usage:

<code class="cpp">std::string result1 = FormatWithCommas(7800);
std::string result2 = FormatWithCommas(5100100);
std::string result3 = FormatWithCommas(201234567890);

// result1 = "7,800"
// result2 = "5,100,100"
// result3 = "201,234,567,890"</code>
Copy after login

Handling Doubles

To format a double as a string with commas, you can use the same approach as above, but the code will need to handle the decimal point:

<code class="cpp">template<class T>
std::string FormatWithCommas(const T& value) {
  std::stringstream ss;
  ss.imbue(std::locale(""));
  ss << std::fixed << std::setprecision(2) << value;
  return ss.str();
}</code>
Copy after login

Disclaimer:

Note that the portability of the above solutions might be an issue, as the locale used when "" is passed may vary depending on the system.

The above is the detailed content of How to Format Numbers with Commas in C Using std::locale?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!