结果显示不带小数

时间:2018-07-24 16:18:47

标签: java android math

有什么办法可以将此计算结果放入不带小数的价格结果中。

 private void calculate() {

    double b = Double.parseDouble(berat.getText().toString());

    if (b <= 0.5) {
        totalPrice1 = 7;
        serviceFee1 = totalPrice1 * 0.2;
        carierFee1 = totalPrice1 * 0.8;
    } else {
        totalPrice1 = b * 12.9;
        serviceFee1 = totalPrice1 * 0.2;
        carierFee1 = totalPrice1 * 0.8;
    }

}

例如,如果我加0.5,则价格结果将在承运人费用中为5.60000000000。我希望将其显示为5.60。

4 个答案:

答案 0 :(得分:1)

尝试一下

DecimalFormat form = new DecimalFormat("0.00");
        String formatedStr = form.format(carrierfee);

答案 1 :(得分:0)

您可以使用DecimalFormat类,例如:

DecimalFormat df = new DecimalFormat("#.00");
String result = df.format(input)

这将输出2个小数点

更多信息链接:https://docs.oracle.com/javase/7/docs/api/java/text/DecimalFormat.html

答案 2 :(得分:0)

如下更新您的功能:

 private void calculate() {

    double b = Double.parseDouble(berat.getText().toString());

    if (b <= 0.5) {
        totalPrice1 = 7;
        serviceFee1 = totalPrice1 * 0.2;
        carierFee1 = totalPrice1 * 0.8;
    } else {
        totalPrice1 = b * 12.9;
        serviceFee1 = totalPrice1 * 0.2;
        carierFee1 = totalPrice1 * 0.8;
    }
    serviceFee1 = Math.round(serviceFee1 * 100.0) / 100.0;
    carierFee1 = Math.round(carierFee1 * 100.0) / 100.0;
}

答案 3 :(得分:0)

有两种显示小数的方法。

  1. DecimalFormat df = new DecimalFormat(“#。00”); 字符串结果= df.format(carierFee1);

    结果将是:   价格= 0.5->结果= 5.6

  2. 字符串结果= String.format(“%.2f”,carierFee1);

    结果将是:   价格= 0.5->结果= 5.60

您可以根据自己的目的选择一个。