Wednesday, July 3, 2024
HomeLanguagesJavaAdding a Character as Thousands Separator to Given Number in Java

Adding a Character as Thousands Separator to Given Number in Java

Given an integer n and character ch, return a String using the character as thousands separator on the given number.

Examples:

Input: n=1234 , ch =’.’

Output: 1.234 

In the above-given input, “.” character is used as the thousands separator and is placed between hundreds and thousands of places starting from the right. The obtained output is returned as String Format.

Input: n=123456789 , ch =’.’

Output: 123.456.789

Approach: 

  1. Convert number into a string.
  2. Start string traversal from the right side.
  3. Add the separator character after every three digits

Below is the code using the same approach using Java.
 

Java




// Java Program for Adding a character as thousands separator
// to the given number and returning in string format
  
class GFG {
  
    static String thousandSeparator(int n, String ch)
    {
  
        // Counting number of digits
        int l = (int)Math.floor(Math.log10(n)) + 1;
        StringBuffer str = new StringBuffer("");
        int count = 0;
        int r = 0;
  
        // Checking if number of digits is greater than 3
        if (l > 3) {
  
            for (int i = l - 1; i >= 0; i--) {
  
                r = n % 10;
                n = n / 10;
                count++;
                if (((count % 3) == 0) && (i != 0)) {
  
                    // Parsing String value of Integer
                    str.append(String.valueOf(r));
  
                    // Appending the separator
                    str.append(ch);
                }
                else
                    str.append(String.valueOf(r));
            }
            str.reverse();
        }
  
        // If digits less than equal to 3, directly print n
        else
            str.append(String.valueOf(n));
  
        return str.toString();
    }
  
    // Driver code
    public static void main(String[] args)
    {
  
        int n = 123456789;
        String ch = ".";
        System.out.println(thousandSeparator(n, ch));
    }
}


Output

123.456.789

Time Complexity: O(n)

Nokonwaba Nkukhwana
Experience as a skilled Java developer and proven expertise in using tools and technical developments to drive improvements throughout a entire software development life cycle. I have extensive industry and full life cycle experience in a java based environment, along with exceptional analytical, design and problem solving capabilities combined with excellent communication skills and ability to work alongside teams to define and refine new functionality. Currently working in springboot projects(microservices). Considering the fact that change is good, I am always keen to new challenges and growth to sharpen my skills.
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments