1

Could you advise on what's the best approach to retrieveting an actual value from differently formatted string numbers?

Example:

I want to be able to pass in all these strings:

101,00
101.00
-101,00
-101.00
100,000.00
100.000,00
-100,000.00
-100.000,00

And get these returns from the method:

101.00
101.00
-101.00
-101.00
100000.00
100000.00
-100000.00
-100000.00

Should I just use string.replaceAll("","") or is there a better way?

Thanks

codaddict
  • 445,704
  • 82
  • 492
  • 529
goe
  • 211
  • 1
  • 4
  • 16

1 Answers1

1

Using replace all won't work. When you need is to find the last occurance of '.' or ',' and use that as your decimal place.

Based on http://docs.oracle.com/javase/tutorial/i18n/format/decimalFormat.html

public static void main(String... args) throws ParseException {
    DecimalFormatSymbols dfs1 = new DecimalFormatSymbols();
    dfs1.setDecimalSeparator('.');
    dfs1.setGroupingSeparator(',');

    DecimalFormat df1 = new DecimalFormat("#,##0.00", dfs1);
    System.out.println(df1.format(-10000)+" parsed is "+df1.parse("-10,000.01"));

    DecimalFormatSymbols dfs2 = new DecimalFormatSymbols();
    dfs2.setDecimalSeparator(',');
    dfs2.setGroupingSeparator('.');

    DecimalFormat df2 = new DecimalFormat("#,##0.00", dfs2);
    System.out.println(df2.format(-10000)+" parsed is "+df2.parse("-10.000,01"));
}

prints

-10,000.00 parsed is -10000.01
-10.000,00 parsed is -10000.01
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
  • Well it would because when the method is called I already know the decimal separator from the application so I don;t have to account for that. So I can definitely do it like that but I wonder if there's a nicer solution to this issue. – goe Apr 27 '12 at 07:50
  • @goe Using DecimalFormat could be considered nicer. – Peter Lawrey Apr 27 '12 at 07:58