Skip to content
Related Articles

Related Articles

Program to format a number with thousands separator in C/C++
  • Last Updated : 31 Oct, 2020

Given an integer N, the task is to print output of the given integer in international place value format and put commas at the appropriate place, from the right.

Examples

Input: N = 47634
Output: 47, 634

Input: N = 1000000
Output : 1, 000, 000

Approach: Follow the steps below to solve the problem:



  1. Convert the given integer N to its equivalent string.
  2. Iterate over the characters of the given string from the right to the left.
  3. After traversing every 3 characters, insert a ‘,’ separator.

Below is the implementation of the above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to implement the
// above approach
  
#include <bits/stdc++.h>
using namespace std;
  
// Function to put thousands
// separators in the given integer
string thousandSeparator(int n)
{
    string ans = "";
  
    // Convert the given integer
    // to equivalent string
    string num = to_string(n);
  
    // Initialise count
    int count = 0;
  
    // Traverse the string in reverse
    for (int i = num.size() - 1;
         i >= 0; i--) {
        count++;
        ans.push_back(num[i]);
  
        // If three characters
        // are traversed
        if (count == 3) {
            ans.push_back(',');
            count = 0;
        }
    }
  
    // Reverse the string to get
    // the desired output
    reverse(ans.begin(), ans.end());
  
    // If the given string is
    // less than 1000
    if (ans.size() % 4 == 0) {
  
        // Remove ','
        ans.erase(ans.begin());
    }
  
    return ans;
}
  
// Driver Code
int main()
{
    int N = 47634;
    string s = thousandSeparator(N);
    cout << s << endl;
}

chevron_right


Output:

47,634

Time Complexity: O(log10N)
Auxiliary Space: O(1)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up
Recommended Articles
Page :