My string is "1234567" and I want to get two big decimal object like these 12345,67 and 12.345,67 but I couldn't do this. Code is shown as below:
DecimalFormat decimalFormat = new DecimalFormat("#,##0.###");
decimalFormat.setParseBigDecimal(true);
String n = decimalFormat.format(1234567);
BigDecimal bigDecimal = (BigDecimal)decimalFormat.parse(n);
DecimalFormat decimalFormat1 = new DecimalFormat("#,0#");
decimalFormat1.setParseBigDecimal(true);
String n1 = decimalFormat.format(1234567);
BigDecimal bigDecimal1 = (BigDecimal)decimalFormat.parse(n1);
System.out.println(n);
System.out.println(bigDecimal);
System.out.println(n1);
System.out.println(bigDecimal1);
Output:
1.234.567,00
1234567.00
1.234.567,00
1234567.00
Expected output:
12.345,67
12.345,67
12345,67
12345,67
Thank you for your help
Number formatting is always locale specific. Therefore a defined locale is needed. Following approach will work for the formatting:
BigDecimal money = new BigDecimal("1234567");
DecimalFormatSymbols symbols = new DecimalFormatSymbols(Locale.GERMAN);
symbols.setDecimalSeparator(',');
symbols.setGroupingSeparator('.');
// https://docs.oracle.com/javase/8/docs/api/java/text/DecimalFormat.html
DecimalFormat format = new DecimalFormat("###,###.00");
format.setDecimalFormatSymbols(symbols);
System.out.println(format.format(money));
However, this does not meet the requirement to parse any given number as a decimal with 2 digits. Here, I would personally would apply a division by 100 or, insert a decimal separator into the given String.
BigDecimal money = new BigDecimal("1234567").divide(new BigDecimal("100"));
Inserting a defined decimal separator could work like this:
private static String prepare(String input) {
if (input.length() == 2) {
return ","+input;
}
if (input.length() == 1) {
return ",0"+input;
}
String integerPart = input.substring(0, input.length()-2);
String fraction = input.substring(input.length()-2);
return integerPart+","+fraction;
}
Using the new DecimalFormat and the prepare()
method it would work to parse a String as a number with 2 decimals by default.
String input = "1234567";
String prepared = prepare(input);
DecimalFormatSymbols symbols = new DecimalFormatSymbols(Locale.GERMAN);
symbols.setDecimalSeparator(',');
symbols.setGroupingSeparator('.');
DecimalFormat format = new DecimalFormat("###,###.00");
format.setDecimalFormatSymbols(symbols);
format.setParseBigDecimal(true);
BigDecimal bigDecimal = (BigDecimal)format.parse(prepared);
String n = format.format(bigDecimal);
System.out.println(n);