-2

I am getting a NumberFormatException although I have StringUtils.isBlank() and I also added a check for a non-breakable white space character, as mentioned in below code:

if (isBlank(amtBeforeTax) || amtBeforeTax.matches("^[\\p{Z}]*$")) {
                ra.setAmtBeforeTax(BigDecimal.ZERO);
            } else {
                ra.setAmtBeforeTax(new BigDecimal(amtBeforeTax));
            }

Still I am getting a number format exception on the on the above piece of code. I do not have the control over the amtBeforeTax, It's a stream of data I am getting and just setting it to some other object. I wanted to know what exactly the precussion i will take over here to avoid the exception.

James Z
  • 12,209
  • 10
  • 24
  • 44
Amar
  • 565
  • 2
  • 8
  • 15
  • `StringUtils.isBlank()` doesn't throw `NumberFormatException` – Karol Dowbecki Feb 12 '19 at 15:20
  • this is not about StringUtils.isBlank() throwing number format exceptions. why the isBlank() not able to trace or the the regex for non breakable white Spaces. How to handle non breakable white spaces. – Amar Feb 12 '19 at 16:20
  • 1
    I think the problem you might be facing is that you need to trim ```amtBeforeTax``` first before you create ```new BigDecimal(amtBeforeTax.trim())```. But just a guess. Anyways Karol Dowbecki anwser is much easier than this so use that. As a side note, there is a dedicated ```NumberUtils.isNumber()``` method which would also help – lifesoordinary Feb 12 '19 at 16:40

1 Answers1

1

One way to solve it is to catch the NumberFormatException, effectively using BigDecimal constructor to perform the validation instead of writing the rules yourself:

try {
  ra.setAmtBeforeTax(new BigDecimal(amtBeforeTax))
} catch (NumberFormatException ex) {
  ra.setAmtBeforeTax(BigDecimal.ZERO);
}
Karol Dowbecki
  • 43,645
  • 9
  • 78
  • 111
  • Thank you..This can be done, But I wanna know why the isBlank() not able to trace or the the regex for non breakable white Spaces. How to handle non breakable white spaces. – Amar Feb 12 '19 at 16:18