Pages

Thursday, November 11, 2010

How to round a double

You 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:
import java.math.*;
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
    }
  }

another way:

double dbl = 12.3456;
int ix = (int)(dbl * 100.0); // scale it
double dbl2 = ((double)ix)/100.0;
System.out.println("dbl=" + dbl + ", dbl2=" + dbl2); //dbl=12.3456, dbl2=12.34

No comments:

Post a Comment