Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract number decimal in BigDecimal

How to extract a number after the decimal point using BigDecimal ?

BigDecimal d = BigDecimal.valueOf(1548.5649);

result : extract only : 5649

like image 581
Mehdi Avatar asked Apr 30 '12 12:04

Mehdi


People also ask

Does BigDecimal have decimal places?

Class BigDecimal. Immutable, arbitrary-precision signed decimal numbers. A BigDecimal consists of an arbitrary precision integer unscaled value and a 32-bit integer scale. If zero or positive, the scale is the number of digits to the right of the decimal point.

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.

Can Biginteger hold decimal values?

BIGINT is to store large integers from negative 263 through positive 263 – 1. The storage size is eight bytes. BIGINT is intended for special cases where INTEGER range is"not sufficient. DECIMAL Valid values are in the range from negative 1038 +1 through positive 1038 – 1.


2 Answers

Try:

BigDecimal d = BigDecimal.valueOf(1548.5649);
BigDecimal result = d.subtract(d.setScale(0, RoundingMode.FLOOR)).movePointRight(d.scale());      
System.out.println(result);

prints:

5649
like image 159
dogbane Avatar answered Sep 18 '22 18:09

dogbane


Try BigDecimal.remainder:

BigDecimal d = BigDecimal.valueOf(1548.5649); 
BigDecimal fraction = d.remainder(BigDecimal.ONE);
System.out.println(fraction);
// Outputs 0.5649
like image 42
Mikita Belahlazau Avatar answered Sep 22 '22 18:09

Mikita Belahlazau