D V
D V

Reputation: 211

Number format exception for decimal number when given double

When I run the following script to check inputQty greater than AvailQty I am getting the following:

java.lang.NumberFormatException: For input string: "97,045.1193"

This error occurs if availableQty is a decimal number. The value is delivered from a database, can you please correct where I am wrong?

   double AvailQty = Double.valueOf(AQTY.getValue());
   double inputQty = Double.valueOf(QTY.getValue());
   if(inputQty > AvailQty){
    session.setStatusMessage("Not Enough Quantity");
    //Abort operation
    throw new AbortHandlerException();
  }

Thanks

Upvotes: 1

Views: 2131

Answers (4)

Cuga
Cuga

Reputation: 17904

Rather than re-formatting the string to do the conversion, you can tell the formatter to read the numbers using whatever format you like.

This answer shows how to change the formatting.

Here's a sample test to show how the same number in your question can be parsed successfully:

 @Test
public void showNumberFormats() throws ParseException {
    String rawAvailQty = "97,045.1193";
    String rawInptQty = "98,045.3421";

    NumberFormat nf = NumberFormat.getNumberInstance();

    double AvailQty = nf.parse(rawAvailQty).doubleValue();
    double inputQty = nf.parse(rawInptQty).doubleValue();
    if(inputQty > AvailQty){
     //Abort operation
     System.err.println("Could not perform operation");
   }
    System.out.println("Available qty: " + AvailQty);
    System.out.println("Input qty: " + inputQty);
}

Prints:

Could not perform operation
Available qty: 97045.1193
Input qty: 98045.3421

Upvotes: 0

Matt
Matt

Reputation: 3353

It can't format it because it doesn't accept the comma. You could do something like Double.valueOf(INV.AVAILQTY.getValue().replaceAll(",", "")) and Double.valueOf(XX_IGL_QTY.getValue().replaceAll(",", "")) to remove any commas before parsing.

Upvotes: 1

Eugen
Eugen

Reputation: 917

Your string contains commas, remove any commas before parsing.

Double.valueOf(INV.AVAILQTY.getValue().replaceAll(",", ""));

Upvotes: 1

Jan Ossowski
Jan Ossowski

Reputation: 338

Simple, your string contains commas. This is not legal. All you can have are numbers and a dot (decimal separator). I don't know where you get the value from, but if it's not something you can change on that side, you will have to do some hacking ;)

Double.valueOf(INV.AVAILQTY.getValue().replaceAll(",","");

Upvotes: 0

Related Questions