1

So i have this code

    BigDecimal bd = new BigDecimal(i);
    bd = bd.round(new MathContext(6));
    double meters = bd.doubleValue();
    double km = bd.doubleValue()*0.001;
    double cm = bd.doubleValue()*100;
    double mm = bd.doubleValue()*1000;
    double miles = bd.doubleValue()*0.000621371192;
    double inches = bd.doubleValue()*39.3700787;
    double feet = bd.doubleValue()*3.2808399;
    double yards = bd.doubleValue()*1.0936133;
    double points = bd.doubleValue()*2834.64567;

So i found an example on here that told me to do it like so

    BigDecimal bd = new BigDecimal(i);
    bd = bd.round(new MathContext(6));
    double meters = bd.doubleValue();

and thats what i tried, and it round the meters number however the inches, feet, yards and so on numbers dont get rounded. am i doing this wrong? what would be the right way to go about this?

EDIT: okay so i found something that has worked in case anyone else ever has a problem with it instead of using :

double points = bd.doubleValue()*2834.64567;

i did this:

BigDecimal points = new BigDecimal(i*2834.64567);
points = points.round(new MathContext(6));
kennie
  • 11
  • 4
  • 2
    I'd use `Double` and [`NumberFormat`](http://docs.oracle.com/javase/7/docs/api/java/text/NumberFormat.html) throughout for this. It seems like pointless overkill to be using a `BigDecimal` when you want only 6 significant digits. – Andrew Thompson Apr 07 '12 at 09:06
  • I think this duplicates/relates to http://stackoverflow.com/questions/153724/how-to-round-a-number-to-n-decimal-places-in-java – joran Apr 07 '12 at 09:24
  • Another possible duplicate - http://stackoverflow.com/questions/202302/rounding-to-an-arbitrary-number-of-significant-digits – luketorjussen Apr 07 '12 at 10:36

1 Answers1

0

You can use BigDecimal; For example:

double d = 15.3343243;
        BigDecimal bd = new BigDecimal(d);
        bd = bd.setScale(2, BigDecimal.ROUND_CEILING);
        bd = new BigDecimal(0.001 * bd.doubleValue());
        d = bd.doubleValue();
        System.out.println(d);

or without BigDecimal objects:

        System.out.println((double)((int) (d * 1000)) / 1000);