Question

Possible Duplicate:
Round a double to 2 significant figures after decimal point

I am trying to work with converting a decimal degree (23.1248) into a minutes style degree(23 7'29.3"). this is what I have so far:

   double a=23.1248;
   int deg=(int)a;//gives me the degree
   float b=(float) (a-deg);
   int min=(int) (b*60);//gives me the minutes
   double sec= (double) ((c*60)-min);//gives me my seconds

everything works fine, but I would like to round the seconds up to either the nearest tenth or hundrenth. I have looked at decimal formatting, but would prefer not to cast it to a string. I have also looked at bigdecimal but do not think that would be helpful,

Was it helpful?

Solution

Try using Math.round(double) on the number after scaling it up, then scaling it back down.

double x = 1.234;
double y = Math.round(x * 100.0) / 100.0; // => 1.23

You can also use BigDecimal if you want to get really heavyweight:

BigDecimal a = new BigDecimal("1.234");
BigDecimal b = a.setScale(2, RoundingMode.DOWN); // => BigDecimal("1.23")

OTHER TIPS

First off, there are library functions to do this, so why not just use those? See Math.round(). No need to reinvent the wheel. If you wanted to, though, you could try what follows. To round a double to the hundredth's place:

x = 0.01 * floor(x * 100.0)

To round a double to the tenth's place:

x = 0.1 * floor(x * 10.0)

To round a double to the 10^k place:

x = 10^k * floor(x / 10^k)

The implementation in any language - including Java - should be straightforward. A problem with this is that it doesn't really round, but truncates, to your position. To fix this, you can simply add 0.5 * 10^k to your number before rounding. If you just want to round up, use the versions above, and add 10^k before or after the computation.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top