四舍五入,同时保持尾随零

Round off a double while maintaining the trailing zero

这是我将数字四舍五入到小数点后两位的函数,但是当四舍五入的数字是 1.50 时,它似乎忽略了尾随零而只是 returns 1.5

public static double roundOff(double number) {
        double accuracy = 20;
        number = number * accuracy;
        number = Math.ceil(number);
        number = number / accuracy;
        return number;
    }

所以如果我发送 1.499 returns 1.5 我想要 1.50

您必须将其格式化为 String 才能做到这一点。 Java 和大多数语言一样,会去掉尾随的零。

String.format("%.2f", number);

因此,您可以 return a String(将 return 类型从双精度更改为),或者仅在需要使用上面的代码显示它时对其进行格式化。您可以 read the JavaDoc for Formatter 了解小数位数、逗号位置等的所有可能性

这是一个打印问题:

double d = 1.5;
System.out.println(String.format("%.2f", d)); // 1.50

1.5 是,尽管有效数字的数量,1.50(甚至 1.5000000000000)相同

您需要将号码的与其表示分开。

如果你想输出两位小数,就用String.format,比如with:

public class Test
{
    public static void main(String[] args) {
        double d = 1.50000;
        System.out.println(d);
        System.out.println(String.format("%.2f", d));
    }
}

输出:

1.5
1.50

如果您仍然想要一个可以为您完成所有操作的函数 并且 为您提供特定格式,则您需要 return 字符串,例如:

public static String roundOff(double num, double acc, String fmt) {
    num *= acc;
    num = Math.ceil(num);
    num /= acc;
    return String.format(fmt, num);
}

并调用它:

resultString = roundOff(value, 20, "%.2f"); // or 100, see below.

这将允许您以任何您想要的方式定制准确性和输出格式,但如果您想要简单,您仍然可以对值进行硬编码:

public static String roundOff(double num) {
    double acc = 20;
    String fmt = "%.2f";
    num *= acc;
    num = Math.ceil(num);
    num /= acc;
    return String.format(fmt, num);
}

最后一点:你的问题表明你想四舍五入到 "two decimals" 但这与你使用 20 作为准确性并不完全一致,因为这会将它四舍五入到<sup>1</sup>/<sub>20</sub> 的下一个倍数。如果您真的希望它四舍五入到两位小数,您应该为accuracy使用的值是100

如果你想要一个字符串输出,你可以试试这个

double number = roundOff(1.499);//1.5

DecimalFormat decimalFormat = new DecimalFormat("#.00");
String fromattedDouble = decimalFormat.format(number);//1.50

函数 roundOff 与您在问题中提到的相同。