Saturday, November 23, 2013

Java decimal numbers to comma-punctuated numbers Conversion

Write a method to convert strings containing decimal numbers into comma-punctuated numbers, with a comma after every third digit from the right.For example, given the string 1234567 , the method should return 1,234,567

SOLUTION: 

import java.util.Scanner;

public class NumberSystem {
 public static void main(String args[]){
  Scanner input = new Scanner(System.in);
  System.out.println("Please enter the number:");
  String num=input.next();
  char[] out = new char[num.length()+25];
  int i=0;
  int j=0;
  int k=0;
  int l=num.length();
  for ( i = 0; i < l; i++ ) {
   out[i+k]=num.charAt(l-i-1);
   j++;
   if(j>2){
    k++;
    out[i+k]=',';
    j=0;
   }
  }
  for ( j = 0; j < k + i; j++ ) {
   if(out[i+k-j-1]==',' && j==0);
   else
   System.out.print(out[i+k-j-1]);
  }
 }
}

No comments:

Post a Comment