Search code examples
javaroundingbigdecimal

BigDecimal not retaining rounded value when converting to/from float


I have a function that rounds a float to n number of digits using BigDecimal.setScale

private float roundPrice(float price, int numDigits) {
    BigDecimal bd = BigDecimal.valueOf(price);
    bd = bd.setScale(numDigits, RoundingMode.HALF_UP);
    float roundedFloat = bd.floatValue();
    return roundedFloat;
}

public void testRoundPrice() {
    float numberToRound = 0.2658f;
    System.out.println(numberToRound);
    float roundedNumber = roundPrice(numberToRound, 5);
    System.out.println(roundedNumber);
    BigDecimal bd = BigDecimal.valueOf(roundedNumber);
    System.out.println(bd);
}

Output:

0.2658
0.2658
0.26579999923706055

How can I prevent BigDecimal from adding all these extra digits at the end of my rounded value?

NOTE: I can't do the following, because I dont have access to the number of digits in the api call function.

System.out.println(bd.setScale(5, RoundingMode.CEILING));

Solution

  • I've decided to modify my program to use BigDecimal as the base type for my property price in my object instead of type float. Although tricky at first it is definitely the cleaner solution in the long run.

    public class Order {
        // float price; // old type
        BigDecimal price; // new type
    }