Search code examples
javanumber-formatting

Parse 2.000,00 to 2000 and 2.000,15 to 2000.15


I am struggling with formatting numbers in java.

My input format looks like this (and I cannot change that): 2.000,15 and the output should look like this: 2000.15

In case of only 0 after the comma the output should look like this: 2000

The input is given as a String.

I've already tried to use a DecimalFormat but this only leads to IllegalArgumentException

DecimalFormat decimalFormat = (DecimalFormat) NumberFormat.getInstance(Locale.ENGLISH);
decimalFormat.setMinimumFractionDigits(0);
decimalFormat.setMaximumFractionDigits(2);
decimalFormat.setGroupingUsed(false);
return decimalFormat.format(Double.parseDouble(characteristicValue));

Solution

  • give this a try:

    NumberFormat fmt = NumberFormat.getInstance(Locale.GERMAN);
            try {
                BigDecimal bd = new BigDecimal(fmt.parse("2.000,15").toString());
                System.out.println(bd.toString()); // output: 2000.15
            } catch (ParseException e) {
                //ex handling
            }