Java

Convoluted Rounding in Java

I was reminded today of how rounding is not given first class treatment in Java. If you want to round an int or long, I suppose some division, casting, and multiplication can suffice, but for float and double, we must resort to the unwieldy BigDecimal class.

Consider the code needed to convert a float of unknown precision to a float with 2 places after the decimal point:

myFloat = (new BigDecimal(myFloat))
    .setScale(2,BigDecimal.ROUND_HALF_UP).floatValue();

Now granted, the rounding flexibility of java.math.BigDecimal is nice, but it’s at least a bit wonky to create 2 additional objects and one extra primitive just to accomplish such a trivial task. (One BigDecimal is created with new(), another with setScale – BigDecimal is immutable.)

Advertisement

3 thoughts on “Convoluted Rounding in Java

  1. Amen!! There’s certain things in java that just aren’t right, and rounding decimals is one of them. Another one is java dates.

    I mean how hard is it to include a nice utility method for simple decimal rounding or for quick and dirty date manipulation. Why do we have to jump through so many hoops???

    Couldn’t they have easily added a wrapper in the Math class such as:
    static double round(double val, scale int)

    How hard is that?

Comments are closed.