【问题标题】:How would I make it so the output will round up to two decimal places?我将如何做到这一点,以便输出将四舍五入到小数点后两位?
【发布时间】:2020-07-04 18:15:53
【问题描述】:

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

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

【问题讨论】:

  • 顺便说一句,千万不要用double来赚钱。使用整数,或使用BigDecimal

标签: java netbeans decimal


【解决方案1】:

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

【讨论】:

  • 它给出了错误“无法编译的源代码 - 错误的树类型:DecimalFormat”
  • 你要导入库,import java.text.DecimalFormat;
  • 它仍然给出了舍入模式部分的错误。它说“找不到符号”
  • 舍入模式库忘记了,import java.math.RoundingMode;
  • 非常感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-26
  • 2022-01-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多