Alex Rivera | Logout

Rounding a double to 5 decimal places in Java ME

Asked 2009-09-20T14:31:45.943
13

How do I round a double to 5 decimal places, without using DecimalFormat?

Edit
Report

4 Answers

8

Multiply by 100000. Add 0.5. Truncate to integer. Then divide by 100000.

Code:

double original = 17.77777777;
int factor = 100000;
int scaled_and_rounded = (int)(original * factor + 0.5);
double rounded = (double)scaled_and_rounded / factor;
answered 2009-09-20T17:11:57.110
2

Try the following

double value = Double.valueOf(String.format(Locale.US, "%1$.5f", 5.565858845));

System.out.println(value); // prints 5.56586

value = Double.valueOf(String.format(Locale.US, "%1$.5f", 5.56585258));

System.out.println(value); // prints 5.56585

Or if you want minimal amount of code

Use import static

import static java.lang.Double.valueOf;
import static java.util.Locale.US;
import static java.lang.String.format;

And

double value = valueOf(format(US, "%1$.5f", 5.56585258));

regards,

answered 2009-09-20T19:01:57.463
2
DecimalFormat roundFormatter = new DecimalFormat("########0.00000");

public Double round(Double d)
    {
        return Double.parseDouble(roundFormatter.format(d));
    }
answered 2010-04-19T21:01:49.770
1
public static double roundNumber(double num, int dec) {
        return Math.round(num*Math.pow(10,dec))/Math.pow(10,dec);
}
answered 2009-09-20T17:10:02.510

Your Answer