Joel
Joel

Reputation: 6211

Convert string to BigDecimal and add Comma Delimiter

I've got a string that i'm reading from a file. This string should be converted to BigDecimal. Once it's in bigdecimal i've got something like this: 000000000103000000. All the 0's before the first number shall be formatted away and the last two 00 should be .00 how would i accomplish this? eg. (000000004711) -> (47.11)

Code:

BigDecimal amount;
String line = "30000000000000010300000000000000000000009876543210";
final NumberFormat formatter = NumberFormat.getInstance(Locale.FRANCE);/* , instead of . */

while((line = inputStream.readLine()) != null) {

    amount = BigDecimal.valueOf(formatter.parse( 
    line.substring(2,24).replaceFirst("^0+(?!$)", "")).longValue());
}

Upvotes: 1

Views: 850

Answers (1)

Youcef LAIDANI
Youcef LAIDANI

Reputation: 60046

You don't need to remove the first zeros, it will be ignored when you convert it to BigDecimal, you just need to put the dot before the two last digits :

String line = "30000000000000010300000000000000000000009876543210";
if (line.length() >= 22) {
    BigDecimal amount = new BigDecimal(
            line.substring(2, 24).replaceFirst("^(.*)(..)$", "$1.$2")
    );
    System.out.println(amount);
}

Output

30000000000000010300000000000000000000009876543210 -> 1030000.00

Upvotes: 3

Related Questions