javaintegerbigdecimalcurrency

How to get Integer of BigDecimal without separator


I need to convert from € to Cents to pass it to another interface.

From a money-object I got BigDecimal 49.99 (€) which I need as Integer 4999 (Cents) - in minor currency unit.

What I tried

Using the integer value like:

BigDecimal bigPrice = moneyPrice.getValue();
Integer price = bigPrice.intValue();

This returns 49 which is not wanted.

I could convert this BigDecimal to String and remove the separator, then parse it to an Integer. But I think this is not pretty.

Question

Given the money amount as BigDecimal,


Solution

  • Try this code:

    BigDecimal db = new BigDecimal("49.99");
    // multiply with 10^scale ( in your case 2)
    db = db.multiply(new BigDecimal(10).pow( db.scale()));
    System.out.println(db.intValue());