I have to convert a German locale formatted String to a BigDecimal. However, I’m struggling with the best solution.
The following code shows my problem:
String numberString = "2.105,88";
NumberFormat nf = NumberFormat.getInstance(Locale.GERMAN);
try {
Number parsed = nf.parse(numberString);
BigDecimal bd1 = new BigDecimal(parsed.toString());
System.out.println(bd1.toString());
BigDecimal bd2 = new BigDecimal(parsed.doubleValue());
System.out.println(bd2);
BigDecimal bd3 = new BigDecimal(numberString);
System.out.println(bd3);
} catch (ParseException e) {
e.printStackTrace();
}
The outpout of this is
2105.88
2105.8800000000001091393642127513885498046875
Exception in thread “main” java.lang.NumberFormatException
at java.math.BigDecimal.(Unknown Source)
at java.math.BigDecimal.(Unknown Source)
at test.BigDecimalTest.main(BigDecimalTest.java:22)
The first output is correct, but it doesn’t really make sense to convert a String to a Number (Double to be precise), then back to a String again and then into a specific type of Number, BigDecimal.
The second output is incorrect, but could be solved by setting the scale of the BigDecimal. However, the amount of digits is not always known.
The third output is obviously not what I’m looking for.
My question: What would be the best way? Are there better ways to do this?
It seems like there is no other way since
java.Lang.Numberdoesn’t have a method which returns aBigDecimaltype. Anyway it makes sense becauseBigDecimalonly accepts strings which are properly formatted not like"2.105,88"but like"2105.88".Let me show your my code:
I hope this helps!