Search code examples
javabigdecimal

Extracting the integer and fractional part from Bigdecimal in Java


I want to extract the integer part and decimal part from the bigdecimal in java.

I am using the following code for that.

    BigDecimal bd = BigDecimal.valueOf(-1.30)
    String textBD = bd.toPlainString();
    System.out.println("length = "+textBD.length());
    int radixLoc = textBD.indexOf('.');
    System.out.println("Fraction "+textBD.substring(0,radixLoc)+"Cents: " + textBD.substring(radixLoc + 1, textBD.length()));

I am getting the output as

-1 and 3

But I want the trailing zero also from -1.30

Output should be -1 and 30


Solution

  • 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