08
Jun
04

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.)


3 Responses to “Convoluted Rounding in Java”


  1. 1 Anonymous
    June 8, 2004 at 10:50 am

    What? Read about DecimalFormat.

  2. 2 Rob Kischuk
    June 8, 2004 at 11:57 am

    I have read about java.text.DecimalFormat. Show me which method returns a rounded float? Not everything is intended as a String for human viewing.

  3. 3 Steve D
    June 8, 2004 at 8:55 pm

    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?


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s



Follow

Get every new post delivered to your Inbox.