Question

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

Était-ce utile?

La solution 2

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

Autres conseils

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.

Initialize with a String to avoid problems with floating point accuracy. Then use setScale to set your desired number of decimal places:

BigDecimal bd = new BigDecimal("-1.30").setScale(2);
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()));
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top