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:
- Convert number into a string.
- Start string traversal from the right side.
- Add the separator character after every three digits
Below is the code using the same approach using Java.
Java
class GFG {
static String thousandSeparator( int n, String ch)
{
int l = ( int )Math.floor(Math.log10(n)) + 1 ;
StringBuffer str = new StringBuffer( "" );
int count = 0 ;
int r = 0 ;
if (l > 3 ) {
for ( int i = l - 1 ; i >= 0 ; i--) {
r = n % 10 ;
n = n / 10 ;
count++;
if (((count % 3 ) == 0 ) && (i != 0 )) {
str.append(String.valueOf(r));
str.append(ch);
}
else
str.append(String.valueOf(r));
}
str.reverse();
}
else
str.append(String.valueOf(n));
return str.toString();
}
public static void main(String[] args)
{
int n = 123456789 ;
String ch = "." ;
System.out.println(thousandSeparator(n, ch));
}
}
|
Time Complexity: O(n)
Last Updated :
04 Nov, 2020
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...