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?
String doubleAsText = "12345.6789"; double number = Double. parseDouble(doubleAsText); int decimal = Integer. parseInt(doubleAsText. split("\.")[0]); int fractional = Integer.
To get the decimal part you could do this: double original = 1.432d; double decimal = original % 1d; Note that due to the way that decimals are actually thought of, this might kill any precision you were after.
intValue() is an in-built function which converts this BigDecimal to an integer value. This function discards any fractional part of this BigDecimal. If the result of the conversion is too big to be represented as an integer value, the function returns only the lower-order 32 bits.
Essentially what you need to do is to first multiply your number by a factor of X so that only the section you want to show is in front of the decimal place, then you can round it using the Math. round function. After that, just divide it back by X in order to put the decimal back in the right spot.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With