Extract number decimal in BigDecimal
17,238
Solution 1
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
Solution 2
Try BigDecimal.remainder:
BigDecimal d = BigDecimal.valueOf(1548.5649);
BigDecimal fraction = d.remainder(BigDecimal.ONE);
System.out.println(fraction);
// Outputs 0.5649
Solution 3
This should do the trick:
d.subtract(d.setScale(0, RoundingMode.FLOOR));
setScale()
rounds the number to zero decimal places, and despite its name, does not mutate the value of d
.
Solution 4
If the value is negative, using d.subtract(d.setScale(0, RoundingMode.FLOOR))
will return a wrong decimal.
Use this:
BigInteger decimal =
d.remainder(BigDecimal.ONE).movePointRight(d.scale()).abs().toBigInteger();
It returns 5649
for 1548.5649
or -1548.5649
Author by
Mehdi
Updated on September 16, 2022Comments
-
Mehdi over 1 year
How to extract a number after the decimal point using BigDecimal ?
BigDecimal d = BigDecimal.valueOf(1548.5649);
result : extract only : 5649
-
Mehdi about 12 yearsit's display : 1548.564900000000079671735875308513641357421875
-
Mehdi about 12 yearsit return a same number : 1548.5649
-
BetaRide about 12 yearsThis works only for a Locale that uses . as the decimal separator. But there are Locales which are using ,.
-
JB Nizet about 12 years@BetaRide: I know that, I'm French speaking, and the comma is used here. But BigDecimal.toPlainString() is not locale-aware. It uses the dot as decimal separator whatever the locale is.
-
diego matos - keke about 8 yearsAs in other topics the result should be "5649" not "0.5649" , this is not the correct answer