Java, extract just the fractional part of a BigDecimal?
Solution 1:
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
Solution 2:
If the value is negative, using bd.subtract()
will return a wrong decimal.
Use this:
BigInteger decimal = bd.remainder(BigDecimal.ONE).movePointRight(bd.scale()).abs().toBigInteger();
It returns 4523434
for 23452.4523434
or -23452.4523434
In addition, if you don't want extra zeros on the right of the fractional part, use:
bd = bd.stripTrailingZeros();
before the previous code.