Issue
I'm parsing out a bunch of numbers from a text-file.
I've isolated the number: 4711,17
from the file which is supposed to be converted into BigDecimal for further processing. (note the comma)
But i am unable to convert it. I get parseExceptions.
public BigDecimal amount; //variable
while((line = inputStream.readLine()) != null) { //reading from file
amount = new BigDecimal(line.substring(17,30)); //parsing out the number
}
Is it because of the comma or what is going on here? (I am unable to change it from a comma to a dot)
Thanks
First line in output looks like this:
O5555 5555555555 4711,17 420110315SEK
Solution
You have 2 issues here:
Extraneous whitespaces
You are trying to parse the following String
: " 4711,17"
.
You need to trim it in order to remove the leading and trailing whitespace characters, using String#trim
.
Using comma (,
) as a decimal separator
Just like parsing Date
s, currencies and even numbers are somewhat Locale
-dependant. In some (many) countries, the comma (,
) is used as a separator for thousands, and the dot (.
) indicates decimals.
Thus, you'll have to specify the Locale
you're working with for your computer to interpret this String
the same way you do (or assume the default Locale
is the one you want).
For instance, let's use the Locale.FRANCE
locale, which does use ,
as a separator for decimals:
// ',' indicates decimals
// v v
final NumberFormat formatter = NumberFormat.getInstance(Locale.FRANCE);
final String line = "O5555 5555555555 4711,17 420110315SEK";
final Number parsed = formatter.parse(line.substring(17, 30).trim());
// ^ ^
// trimmed
Using the snippet above, you'll be left with a Number
whose value is the one you want :)
Since you're looking for a BigDecimal
though, I'd simply use BigDecimal.valueOf(parsed .doubleValue())
to 'convert' it, like so:
final BigDecimal amount = BigDecimal.valueOf(formatter.parse(line.substring(17, 30).trim()).doubleValue());
Incorporating this into your piece of code would give:
BigDecimal amount;
while((line = inputStream.readLine()) != null) {
amount = BigDecimal.valueOf(formatter.parse(line.substring(17, 30).trim()).doubleValue());
}
Answered By - ccjmne
Answer Checked By - Marilyn (JavaFixing Volunteer)