How to parse String to BigDecimal without error
When I want to parse a value from a String array to BigDecimal I have this error:
Exception in thread "main" java.text.ParseException: Unparseable number: "86400864008640086400222"
I'm looking online for a solution on how to fix this. Maybe you guys know?
It's not my idea to use BigDecimal, but unfortunately I need it. I have based some code that is supposed to change the value from String to BigDecimal and return it:
public static BigDecimal parseCurrencyPrecise (String value) throws ParseException
{
NumberFormat format = NumberFormat.getCurrencyInstance ();
if (format instanceof DecimalFormat)
((DecimalFormat) format).setParseBigDecimal (true);
Number result = format.parse (value);
if (result instanceof BigDecimal)
return (BigDecimal) result;
else {
// Oh well...
return new BigDecimal (result.doubleValue ());
}
}
Here is my code when trying to parse:
public void Function() throws ParseException {
String [] array;
array=OpenFile().split("\\s");
for(int i = 10 ;i < array.length; i+= 11) {
BigDecimal EAE = parseCurrencyPrecise(array[i]);
System.out.println(EAE);
}
}
The OpenFile function opens a data file and reads it this way L temp + = line + ""; This is why I split into \ s. This work for me with strings and integers, but I have a problem with BigDecimal.
Hello,
source to share
Instead of dealing with parsing, you can use the constructor BigDecimal(String val)
. From Javadoc
BigDecimal(String val)
Translates the string representation of a BigDecimal into a BigDecimal
For example:
BigDecimal bigDecimal = new BigDecimal("86400864008640086400222");
See the Javadoc for the formats the constructor accepts.
source to share