如何在Java中获取下一个更高的十进制值,四舍五入到小数点后一位?

时间:2018-08-15 11:12:58

标签: java math

我有两个双打,如下所示:011490.2和011500.1 我想用java打印此范围内的所有双精度数,四舍五入到小数点后一位。我该怎么办?

这是我到目前为止尝试过的方法,但是它正在某种无限循环中进行:

            Double a = Double.parseDouble(temp[0].subSequence(temp[0].indexOf("g")+1, temp[0].length()).toString());
            Double b = Double.parseDouble(temp[1].subSequence(temp[0].indexOf("g")+1, temp[1].length()).toString());
            int count = 0;
            while (b >= a) {
                count++;
                System.out.println("printing range:" + Math.round(Math.nextUp(a));

            }

我想要打印这样的东西: 011490.2 011490.3 011490.4 011490.5 011490.6 011490.7 011490.8 011490.9 011490.2 011490.3 011490.4 011491.1 011491.2 011491.3 011491.4 011491.5 。 。 。 。 011500.1

4 个答案:

答案 0 :(得分:3)

为完整起见,这是for循环方式:

    double start = 11490.2D;
    double end = 11500.1D;

    for(double i = start; i < end + 0.05; i += 0.1) {
        System.out.printf("%.1f\n", i);
    }

编辑:根据亨利的评论进行更新

答案 1 :(得分:2)

double a = Double.parseDouble("011490.2");
double b = Double.parseDouble("011500.1");
int count = 0;
while (a <= (b + 0.1)) {
    System.out.printf("printing range: 0%.1f\n",a);
    a = a+0.1;
}

输出:

printing range: 011490.2
printing range: 011490.3
printing range: 011490.4
printing range: 011490.5
printing range: 011490.6
printing range: 011490.7
...
...
...
printing range: 011499.6
printing range: 011499.7
printing range: 011499.8
printing range: 011499.9
printing range: 011500.0
printing range: 011500.1

答案 2 :(得分:2)

这是我的变种

double a = 11490.2;
double b = 11500.1;

while (a <= (b + 0.01)) {
    System.out.printf("0%.1f ", a); //Change to System.out.printf("0%.1f \n", a); if you want each value on a new row
    a += 0.1;
}

答案 3 :(得分:1)

如何?

    do {
        System.out.println(decimalFormat.format(a));
        a = a + 0.1;
    } while (b >= a);

    System.out.println(decimalFormat.format(a));