I have to convert a German locale formatted String
to a BigDecimal
. However, I\'m struggling with the best solution.
The following code sho
The Problem is the formatting of your String. You should go with the 3rd Method, but format your String like this: String numberString = "2105.88";
You will be able to see this from the given examples here: Link to Java Api
Edit: Ok, so I see 2 possible solutions for this. Either go with your solution 1 (That's what I prefer) or do something like:
numberString = numberString.replaceAll(".", "");
numberString = numberString.replaceAll(",", ".");
BigDecimal bd3 = new BigDecimal(numberString);
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 formated
System.out.println(new BigDecimal(numberStringFixed));;
//direct but erroneous way if the string is not formated
System.out.println(new BigDecimal(numberString));;
}
}
I hope this helps!
DecimalFormat
has a method called setParseBigDecimal that causes parse()
to return a BigDecimal
. You just need to cast the returned Number
.
String numberString = "2.105,88";
NumberFormat nf = NumberFormat.getInstance(Locale.GERMAN);
if (nf instanceof DecimalFormat) {
DecimalFormat df = (DecimalFormat) nf;
df.setParseBigDecimal(true);
BigDecimal parsed = (BigDecimal) df.parse(numberString);
System.out.println(parsed);
}
Output:
2105.88
setParseBigDecimal
was introduced in Java 1.5.