我该怎么做才能使输出四舍五入到小数点后两位?

How would I make it so the output will round up to two decimal places?

我的代码在这里工作正常,但每当我 运行 它时,它似乎没有四舍五入,我不知道要添加什么以及在哪里添加它。

package com.mycompany.billofsale;

public class Billofsale {
    public static void main(String[] args) {
        double s = 12.49;
        double p = 20.00;
        double t = 0.13;
        double result = s * t;
        double result2 = s + result;
        double result3 = p - (s + result);
        System.out.println("The total is "+s
                + "\n The tax is "+result
                + "\n The total cost with tax is "+result2
                + "\n The change is "+result3);
    }
}

您需要使用 DecimalFormat 将所有要打印的数字格式化为您想要的小数。

尝试使用此代码:

double s = 12.49;
    double p = 20.00;
    double t = 0.13;
    double result = s * t;
    double result2 = s + result;
    double result3 = p - (s + result);
    DecimalFormat format = new DecimalFormat(".00");
    format.setRoundingMode(RoundingMode.HALF_UP);
    System.out.println("The total is " + s + "\n The tax is " +format.format(result) + "\n The total cost with tax is " + format.format(result2)
            + "\n The change is " + format.format(result3));