0

I got the following BigDecimal from a Money-Object: BigDecimal 49.99 and I need this as Integer 4999, so everything I ask for is getting rid of the separator.

I could get this BigDecimal as String and remove the separator and parse it to an Integer, but I do not think that this is pretty.

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

Using this only responses with 49.

PreDer
  • 113
  • 3
  • 11

4 Answers4

3

You need the method:

movePointRight(int n)

javadoc link: http://docs.oracle.com/javase/6/docs/api/java/math/BigDecimal.html#movePointRight(int)

example:

    BigDecimal bd = new BigDecimal("398.0275");
    System.out.println(bd.movePointRight(bd.scale()));

outputs:

3980275

If you want to use the number, just bd=bd.movePointRight(bd.scale());

Kent
  • 189,393
  • 32
  • 233
  • 301
1

If it's currency and always to 2 dp, you could multiple it by 100. However as Davio comments, your code should make it clear why you're doing it.

If you want to convert, for example a price in GB pounds sterling to GB pence (100 pence in a pound) then multiplying it by 100 is the right thing to do.

cf_en
  • 1,661
  • 1
  • 10
  • 18
1

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());
Jens
  • 67,715
  • 15
  • 98
  • 113
1

It's not necessary to do any math on the BigDecimal; you can just call myBigDecimal.unscaledValue() to get the underlying unscaled BigInteger directly.

Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413