Java, extract just the fractional part of a BigDecimal?
JavaBigdecimalJava Problem Overview
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?
Java Solutions
Solution 1 - Java
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 - Java
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.
Solution 3 - Java
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();
Solution 4 - Java
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