Skip to content
August 31, 2009 / edivad

rounding double in java

Credits: Gabri Le Cabri (from flickr)

Credits: Gabri Le Cabri (from flickr)

Rounding a double in java is very simple. If you have to round it to the nearest integer you could use the Math.round(double) method, but what about if you have to round it with a desired number of decimals?

Quite easy too. Using the BigDecimal.setScale(int,int) method you can choose how to round it. Following a quick example:

BigDecimal bd = new BigDecimal(123.45);
bd = bd.setScale(1,BigDecimal.ROUND_HALF_UP);
System.out.println(bd.doubleValue()); //should output 123.5

One Comment

Leave a Comment
  1. Alex Gonzalo / Feb 23 2011 9:20 pm

    If value is 100.85 return 100.8 , but is 100.9 .. why?

    BigDecimal bd = new BigDecimal(100.85);
    bd = bd.setScale(1,BigDecimal.ROUND_HALF_UP);
    System.out.println(bd.doubleValue());

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.