Wassim Abbas
Wassim Abbas

Reputation: 41

Convert an array of string to an array of BigDecimals

I'm trying to convert a String[] to BigDecimal[] but i'm getting java.lang.NumberFormatException

this is my code

BigDecimal montanttt[] = new BigDecimal[montantt.length];
        for (int i = 0; i < montantt.length; i++) {
            montanttt[i] = new BigDecimal(montantt[i]);
            System.out.println(montanttt[i]);
        }

Upvotes: 2

Views: 6109

Answers (4)

Charif DZ
Charif DZ

Reputation: 14721

try this:

BigDecimal montanttt[] = new BigDecimal[montantt.length];
    for (int i = 0; i < montantt.length; i++) {
        try {
         montanttt[i] =BigDecimal.valueOf(Double.valueOf(montantt[i]))
        System.out.println(montanttt[i]);
    } catch (Exception e) {
      e.printStackTrace();
    }           
    }

Upvotes: 1

Alex Salauyou
Alex Salauyou

Reputation: 14338

Try to clear all chars that are not part of number and normalize decimal point before parsing, like:

String normalized = montantt[i].replace(",", ".").replaceAll("[^-.0-9eE]", "");
BigDecimal d = new BigDecimal(normalized);

Upvotes: 1

Andrew
Andrew

Reputation: 49606

The compact solution on Java 8 is here.

Arrays.stream(montantt).map(s -> {
        try { 
            return new BigDecimal(s);
        } catch (NumberFormatException e) {
            return BigDecimal.ZERO;
        }
}).toArray(BigDecimal[]::new);

You will get NumberFormatException if String cannot be converted to BigDecimal. But you can return some constant if the exception was thrown, for example BigDecimal.ZERO.


It works fine for your input ["0.50","0.20"].

Upvotes: 2

Cootri
Cootri

Reputation: 3836

You should check for exception using try/catch in the for loop:

for (int i = 0; i < montantt.length; i++) {
    try {
        montanttt[i] = new BigDecimal(montantt[i]);
        System.out.println(montanttt[i]);
    } catch (NumberFormatException e) {
        System.out.println("Exception while parsing: " + montantt[i]);
    }
}

Upvotes: 3

Related Questions