首页 > 解决方案 > 我将如何做到这一点,以便输出将四舍五入到小数点后两位?

问题描述

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

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);
    }
}

标签: javanetbeansdecimal

解决方案


您需要使用 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));

推荐阅读