[Last Call] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 276
  • Last Modified:

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.




0
applekanna
Asked:
applekanna
  • 4
  • 2
1 Solution
 
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
 
objectsCommented:
Actually you only need one, something like:

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

0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
objectsCommented:
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:
thx you :)
0
 
objectsCommented:
no worries :)
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 4
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now