Best way to convert Locale specific String to BigDecimal
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.
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!