Rounding a double to 5 decimal places in Java ME

2020-02-05 07:49发布

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

8条回答
虎瘦雄心在
2楼-- · 2020-02-05 08:34

You can round to the fifth decimal place by making it the first decimal place by multiplying your number. Then do normal rounding, and make it the fifth decimal place again.

Let's say the value to round is a double named x:

double factor = 1e5; // = 1 * 10^5 = 100000.
double result = Math.round(x * factor) / factor;

If you want to round to 6 decimal places, let factor be 1e6, and so on.

查看更多
一纸荒年 Trace。
3楼-- · 2020-02-05 08:34
public static double roundNumber(double num, int dec) {
        return Math.round(num*Math.pow(10,dec))/Math.pow(10,dec);
}
查看更多
登录 后发表回答