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?
math. BigDecimal. valueOf(double val) is an inbuilt method in java that translates a double into a BigDecimal, using the double's canonical string representation provided by the Double. toString(double) method.
It seems like there is no other way since java.Lang.Number
doesn't have a method which returns a BigDecimal
type. Anyway it makes sense because BigDecimal
only accepts strings which are properly formatted not like "2.105,88"
but like "2105.88"
.
Let me show your my code:
import java.math.BigDecimal; import java.text.DecimalFormat; import java.text.NumberFormat; import java.text.ParseException; import java.util.Locale; public class JavaMain { public static void main(String[] args) { String numberString = "2.105,88"; //using casting try { DecimalFormat df = (DecimalFormat) NumberFormat.getInstance(Locale.GERMAN); df.setParseBigDecimal(true); BigDecimal bd = (BigDecimal) df.parseObject(numberString); System.out.println(bd.toString()); } catch (ParseException e) { e.printStackTrace(); } //your way short version NumberFormat nf = NumberFormat.getInstance(Locale.GERMAN); try { BigDecimal bd1 = new BigDecimal(nf.parse(numberString).toString()); System.out.println(bd1.toString()); } catch (ParseException e) { e.printStackTrace(); } String numberStringFixed = "2105.88"; //direct string formatted System.out.println(new BigDecimal(numberStringFixed));; //direct but erroneous way if the string is not formatted System.out.println(new BigDecimal(numberString));; } }
I hope this helps!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With