Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rounding decimal points [duplicate]

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,

like image 862
Paul Robert Carlson Avatar asked Jan 11 '12 19:01

Paul Robert Carlson


People also ask

How do you round a double to two decimal places?

We can use DecimalFormat("0.00") to ensure the number always round to 2 decimal places.

Should two decimal places be rounded?

Rounding a decimal number to two decimal places is the same as rounding it to the hundredths place, which is the second place to the right of the decimal point. For example, 2.83620364 can be round to two decimal places as 2.84, and 0.7035 can be round to two decimal places as 0.70.


1 Answers

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")
like image 174
maerics Avatar answered Sep 19 '22 02:09

maerics