I have a below program which is reading and displaying decimal numbers.
import java.math.*;
import java.text.DecimalFormat;
import java.text.ParseException;
public class Main {
public static void main (String[] args) {
String valStr = "-5.36870912E+9";
Object val = null;
DecimalFormat mDecimalFormat = new DecimalFormat("#.#");
mDecimalFormat.setParseBigDecimal(true);
mDecimalFormat.setMaximumFractionDigits(38);
try {
val = new BigDecimal(mDecimalFormat.parse(valStr).toString());
System.out.println("valStr = " + valStr + " val = " + val + " mDecimalFormat.parse(valStr) " + mDecimalFormat.parse(valStr));
}
catch (ParseException ee) {
System.out.println("Caught Exception");
}
}
}
It generates a below output.
valStr = -5.36870912E+9 val = -5.36870912 mDecimalFormat.parse(valStr) -5.36870912
Here the issue is, parse ignores the exponential format.
I tried to use below code with BigDecimal and it works fine.
BigDecimal temp = new BigDecimal(valStr);
val = new BigDecimal(mDecimalFormat.parse(temp.toPlainString()).toString());
Output with above changes are
valStr = -5.36870912E+9 val = -5368709120 mDecimalFormat.parse(valStr) -5.36870912
But the problem is, if I try to use inputs from different locale, For example, French as shown below.
String valStr = "-5,36870912E+9";
Ending up with below exception.
Exception in thread "main" java.lang.NumberFormatException: Character , is neither a decimal digit number, decimal point, nor "e" notation exponential mark.
at java.base/java.math.BigDecimal.<init>(BigDecimal.java:522)
at java.base/java.math.BigDecimal.<init>(BigDecimal.java:405)
at java.base/java.math.BigDecimal.<init>(BigDecimal.java:838)
at Main.main(Main.java:14)
I have referred various pages, most of the suggestions were to use BigDecimal, Double.
Is there any way i could convert the string “-5,36870912E+9” to “-5368709120” before calling parse method?
10