RAD Studio 10.4.1 is now available! Learn more. Looking for discounts? Visit our Special Offers page!
C++

Output Numbers with Thousands Separator

Author: Embarcadero USA

 Technical Information Database

TI2183C.txt   Output Numbers with Thousands Separator
Category   :General
Platform    :All
Product    :C/C++  All

Description:
How do I output comma-formatted numbers such as 1,000,000 with
C++ IOStreams?  As common as this would seem, C++ IOStreams have
no support for this.  The function shown in the code sample below
serves two purposes: it converts the long to a string and inserts
commas every three digits.  Adding the commas during the
conversion is much easier than converting the long to a string
using sprintf() and then modifying the string.
For new programmers, this code is an excellent example use of
the modulus operator to reverse a string.  The reversing
algorithm is almost identical to the generic reverse() function
in the Standard Template Library.
#include 
const char *commaStr(unsigned long number)
{
  const int size = 15;    // max number of digits
  static char str[size];  // string to return
  char *ptr1, *ptr2;      // place holders
  char tempStr[size];     // workplace
  int counter = 0;        // three's counter
  ptr1 = tempStr;
  do {
    // grab rightmost digit and add value of character zero
    *ptr1++ = (char)(number % 10) + '0';
    // strip off rightmost digit
    number /= 10;
    // if moved over three digits insert comma into string
    if (number &&  !(++counter % 3))
      *ptr1++ = ',';
    // continue until number equal zero
  } while(number);
  // this loop reverses characters in a string
  for( --ptr1, ptr2 = str; ptr1 >= tempStr; --ptr1)
    *ptr2++ = *ptr1;
  // add the zero string terminator
  *ptr2 = '0';
  return str;
}
// simple main to test function
int main() {
   cout <<'s "Toolbox".  If you're
new to programming, it will be worth your time to run the code
in the debugger and watch how it works.  Use
Debug|Evaluate|Modify to see how the modulus works.  Then
inspect the pointer in the reverse code to understand how it
accomplishes its task.
CAVEATS
=======
N/A
BIBLIOGRAPHY
============
N/A


Reference:


7/2/98 10:40:36 AM
 

Article originally contributed by


Reduce development time and get to market faster with RAD Studio, Delphi, or C++Builder.
Design. Code. Compile. Deploy.
Start Free Trial   Upgrade Today

   Free Delphi Community Edition   Free C++Builder Community Edition

Related posts
News

Using C++17 Algorithms Library Parallel Sorting with C++Builder 10.4 Sydney for Win32 and Win64

C++News

C++Builder and Platforms Support

C++

What's New in the GetIt Package Manager - June 2020

C++

RAD Studio 10.4 Now Available, Learn More

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

IN THE ARTICLES