Search code examples
javabigdecimal

Java, extract just the fractional part of a BigDecimal?


In Java, I'm working with the BigDecimal class and part of my code requires me to extract the fractional part from it. BigDecimal does not appear to have any built in methods to help me get the number after the decimal point of a BigDecimal.

For example:

BigDecimal bd = new BigDecimal("23452.4523434");

I want to extract the 4523434 from the number represented above. What's the best way to do it?


Solution

  • I would try bd.remainder(BigDecimal.ONE).

    Uses the remainder method and the ONE constant.

    BigDecimal bd = new BigDecimal( "23452.4523434" );
    BigDecimal fractionalPart = bd.remainder( BigDecimal.ONE ); // Result:  0.4523434