Java, extract just the fractional part of a BigDecimal?
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
Here's an alternative to using the remainder()
method:
BigDecimal bd = new BigDecimal("23452.4523434");
BigDecimal fracBd = bd.subtract(new BigDecimal(bd.toBigInteger()));
Further, you can try the abs() method to ensure the fraction part is positive:
BigDecimal fracBd = bd.subtract(new BigDecimal(bd.toBigInteger())).abs();
It doesn't work!!!
BigDecimal d = BigDecimal.valueOf(23452.4523434);
BigInteger decimal =
d.remainder(BigDecimal.ONE).movePointRight(d.scale()).abs().toBigInteger();
When you input number, which fractional-part starts with '0', for ex. "123.00456".
You get "456" instead of "00456".
It happens because we convert it .toBigInteger()
, and the first zeros just gone;
If you use .toString()
instead of .toBigInteger()
, you get 456.00000, it's wrong too!
So my advise is using this:
BigDecimal fractPart = bd.remainder(BigDecimal.ONE);
StringBuilder sb = new StringBuilder(fractPart.toString());
sb.delete(0, 2);
String str = sb.toString();
And then just use this str
how you want
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.