1

我在谷歌上搜索的所有内容都表明以下任何一项都会将双精度舍入到小数点后两位。

double roundToFourDecimals(double d)
{
    DecimalFormat twoDForm = new DecimalFormat("#.##");
    double myD = Double.valueOf(twoDForm.format(d));
    return myD;
}

double nextLon = (double)Math.round(bnextLon * 100.0) / 100.0;

但两者都不适合我。double 的值是3.3743984E7和结果是一样的。怎么了?

4

2 回答 2

5

Nothing's wrong. 3.3743984E7 is scientific notation. That is:

3.3743984E7 = 3.3743984 * 10^7 = 33743984

33,743,984.0 rounded to two decimal places is 33,743,984.0. If, perhaps you specified 33743984.05918, it would be rounded to 33743984.06, but both outputs would still say 3.3743984E7. (The preceding comment has been deleted due to invalidity found by @Sam.)

I can verify that your rounding code works:

public class Main {
    public static void main(String[] args) {
        double bnextLon = 275914.18410;
        double nextLon = (double) Math.round(bnextLon * 100.0) / 100.0;
        System.out.println(bnextLon + " became " + nextLon);
    }
}

275914.1841 became 275914.18

I believe you simply need to determine what value you want in, and what value you want out. The code is giving you exactly what you're specifying.

于 2012-12-18T23:44:34.377 回答
2

3.3743984E7 means 33743984, so multiplying by 100 gives 3374398400, then rounding change nothing, then division goes back.

You should divide by 1E5 then round, than back.

于 2012-12-18T23:45:54.990 回答