Home > Dev Stuffs, Java > How to round a double using Java

How to round a double using Java

JavaYou can round a double using the setScale() method of BigDecimal class. This method is vlaid after Java 1.1. An example of doing this is shown below:

public class Divers {
public static void main(String args[]){
Divers d = new Divers();
d.testRound();
}

public void testRound(){
double r = 3.1537;
int decimalPlace = 2;
BigDecimal bd = new BigDecimal(r);
bd = bd.setScale(decimalPlace,BigDecimal.ROUND_UP);
r = bd.doubleValue();
System.out.println(r); // output is 3.15
}
}

Or do like I did, create a simple method like this:
public static double round(double d, int decimalPlace) {
BigDecimal bd = new BigDecimal(Double.toString(d));
bd = bd.setScale(decimalPlace, BigDecimal.ROUND_HALF_UP);
return bd.doubleValue();
}

  1. No comments yet.
  1. No trackbacks yet.

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 )

Google+ photo

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

Connecting to %s

%d bloggers like this: