Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 328
Franklin Avatar asked Apr 06 '12 03:04

Franklin


People also ask

How do you extract a fractional part in Java?

String doubleAsText = "12345.6789"; double number = Double. parseDouble(doubleAsText); int decimal = Integer. parseInt(doubleAsText. split("\.")[0]); int fractional = Integer.

How do you extract the decimal part of a number in Java?

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.

How do you get the integer part in BigDecimal?

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.

How do you round fractions in Java?

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.


2 Answers

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 
like image 174
Taymon Avatar answered Oct 13 '22 19:10

Taymon


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.

like image 35
IvanRF Avatar answered Oct 13 '22 19:10

IvanRF