Extracting integer and fractional parts from Bigdecimal in Java

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

I use the following code for this.

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 get output as

-1 and 3

But I want the trailing zero also to be -1.30

The output should be -1 and 30

+6
source share
3 answers

The -1.30 floating point representation is not accurate. Here is a small modification to 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 set RoundingMode to setScale to round fractional pennies, for example, 1.295 half-up to 1.30.

Results:

 text version, length = <-1.30>, 5 Fraction -1. Cents: 30 
+4
source

If you like not to interfere with Strings (which, I think, is not a good practice - other than creating BigDecimal), you can only do this 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 fix it if you understand what I was trying to say. Thanks.

+3
source

Initialize with String to avoid floating point precision issues. Then use setScale to set the required 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())); 
+1
source

All Articles