simple string parsing

I have a string say 15000000.00 and I need to format it like 15,000,000.00 basically add the commas for ease of readbility.




LVL 3
applekannaAsked:
Who is Participating?
 
objectsConnect With a Mentor Commented:
sorry that should be:

double d = Double.parseDouble(amt);
DecimalFormat df = new DecimalFormat("###,###,###.00");
return df.format(d);


you don't actually need to create df everytime it is called and instead make it a class or member variable.

0
 
applekannaAuthor Commented:
 public  String format(String amt, )
  {
    String result = "";
    String pre = amt.substring(0, amt.indexOf("."));
    StringBuffer buff = new StringBuffer(pre);
    buff = buff.reverse();
    System.out.println("buff length" + buff.length());
    int len = buff.length();
    int currpos = 0;
    for(;;)
    {
      result = result+ buff.substring(currpos, currpos+3)+",";
      currpos = currpos+3;
      if(!(len -currpos > 3)) break;
    }
    result = result + buff.substring(currpos, len) ;
    buff = new StringBuffer(result);
    result =  buff.reverse().toString()+  amt.substring(amt.indexOf("."), amt.length());
    return result;
  }


this is my solution ..but i think it can be done better
0
 
objectsCommented:
Use two NumberFormat's, onr to parse it, and the other to reformat it.
0
The 14th Annual Expert Award Winners

The results are in! Meet the top members of our 2017 Expert Awards. Congratulations to all who qualified!

 
objectsCommented:
Actually you only need one, something like:

double d = Double.parseValue(amt);
DecimalFormat df = new DecimalFormat("###,###,###.00");
return df.format(d);

0
 
applekannaAuthor Commented:
thx you :)
0
 
objectsCommented:
no worries :)
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.