2

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]);
        }
8
  • 1
    What is the content of montantt? Commented Mar 31, 2016 at 9:38
  • String[] montantt = request.getParameterValues("montant"); Commented Mar 31, 2016 at 9:39
  • What is the content of request.getParameterValues("montant");? Commented Mar 31, 2016 at 9:40
  • I think he means what is the actual string content. For example ['James', 'Harry', '2']. Commented Mar 31, 2016 at 9:40
  • Please also give your variables better names.. Now it so easy to confuse montanttt and montantt Commented Mar 31, 2016 at 9:41

4 Answers 4

3

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]);
    }
}
Sign up to request clarification or add additional context in comments.

Comments

2

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"].

1 Comment

If montantt contains invalid strings, that won't help much.
1

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);

Comments

1

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();
    }           
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.