Extracting the integer and fractional part from Bigdecimal in Java
The floating point representation of -1.30 is not exact. Here is a slight modification of your code:
BigDecimal bd = new BigDecimal("-1.30").setScale(2, RoundingMode.HALF_UP);
String textBD = bd.toPlainString();
System.out.println("text version, length = <" + textBD + ">, " + textBD.length());
int radixLoc = textBD.indexOf('.');
System.out.println("Fraction " + textBD.substring(0, radixLoc)
+ ". Cents: " + textBD.substring(radixLoc + 1, textBD.length()));
I have put a RoundingMode on the setScale to round fractional pennies like 1.295 "half up" to 1.30.
The results are:
text version, length = <-1.30>, 5
Fraction -1. Cents: 30
If you like to not get involved with Strings (which I think it's not good practice - except the part of creating de BigDecimal) you could do it just with Math:
// [1] Creating and rounding (just like GriffeyDog suggested) so you can sure scale are 2
BigDecimal bd = new BigDecimal("-1.30").setScale(2, RoundingMode.HALF_UP);
// [2] Fraction part (0.30)
BigDecimal fraction = bd.remainder(BigDecimal.ONE);
// [3] Fraction as integer - move the decimal.
BigDecimal fraction2 = fraction.movePointRight(bd.scale());
// [4] And the Integer part can result of:
BigDecimal natural = bd.subtract(fraction);
// [5] Since the fraction part of 'natural' is just Zeros, you can setScale(0) without worry about rounding
natural = natural.setScale(0);
I know, my english is terrible. Feel free to correct if you could understand what I tried to say. Thanks.