-1

I have a string that shows a number with a comma separator like this:

DecimalFormat formatter = new DecimalFormat("#,###.000000");
String toDouble=formatter.format(amount);

Now I want to remove commas in BO class to do arithmetic operations. I used this format:

StrCash_price_deal = StrCash_price_deal.replace(",", "");
double d = Double.valueOf(StrCash_price_deal.trim()).doubleValue();

but it changes the value to zero!!! my technology is struts2

Steven Benitez
  • 10,936
  • 3
  • 39
  • 50
AFF
  • 1,515
  • 4
  • 21
  • 35
  • Possible duplicate : http://stackoverflow.com/questions/11981361/comma-separator-in-a-string-variable – KV Prajapati Aug 16 '12 at 08:17
  • In your last [question](http://stackoverflow.com/questions/11981361/comma-separator-in-a-string-variable) you wanted to add commas. Now you want to delete them. Maybe you should describe what you are actually trying to achieve... – maba Aug 16 '12 at 08:18
  • yes my customer wants to see number in comma separation but I have to do arithmetic operations on it, so I have to drop commas – AFF Aug 16 '12 at 08:20

1 Answers1

5

You have a DecimalFormat which you're using to format the value. Use the same object to parse the value, instead of using Double.valueOf.

Additionally:

  • Try to avoid formatting/parsing cycles where possible. Keep the value as a number for almost your whole code base, only formatting for presentation and only parsing for user input
  • Don't use double for currency values; use BigDecimal which will reduce the surprises you get when it comes to "inaccurate" arithmetic
  • Follow Java naming conventions wherever possible. StrCash_price_deal is horrible in both casing and underscore-ness
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194