0

I used BigDecimal for rounding money value. And I have question.

    float price = 0.71F;
    BigDecimal priceA = BigDecimal.valueOf(price).setScale(2, RoundingMode.FLOOR);
    //priceA == 0.70;

    float price = 8.71F;
    BigDecimal priceB = BigDecimal.valueOf(price).setScale(2, RoundingMode.FLOOR);
    //priceB == 8.71;

Why ? And how rounding write ?

smail2133
  • 936
  • 2
  • 7
  • 24

1 Answers1

0

Never construct BigDecimals from floats or doubles. Construct them from ints or strings. floats and doubles loose precision.

This code works as expected. I just changed the type from float to String:

public static void main(String[] args) {
  String doubleVal = "1.745";
  String doubleVal1 = "0.745";
  BigDecimal bdTest = new BigDecimal(  doubleVal);
  BigDecimal bdTest1 = new BigDecimal(  doubleVal1 );
  bdTest = bdTest.setScale(2, BigDecimal.ROUND_HALF_UP);
  bdTest1 = bdTest1.setScale(2, BigDecimal.ROUND_HALF_UP);
  System.out.println("bdTest:"+bdTest); //1.75
  System.out.println("bdTest1:"+bdTest1);//0.75, no problem
}
smail2133
  • 936
  • 2
  • 7
  • 24