繁体   English   中英

在保持尾随零的同时舍入双倍

[英]Round off a double while maintaining the trailing zero

这是我的函数来舍入一个最多两位小数的数字但是当舍入数字是1.50时它似乎忽略了尾随零并且只返回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,则返回1.5,因为我想要1.50

这是一个印刷问题:

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

1.5是尽管有效位数,但 1.50 (甚至1.5000000000000 )相同。

您需要将数字的与其显示分开

如果您希望它输出两个十进制数字,只需使用String.format ,例如:

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

如果您仍然需要一个能够为您完成所有操作为您提供特定格式的函数,则需要返回以下内容:

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

最后一点:你的问题指出,要舍入到“两位小数”,但完全不是那么回事凝胶与您使用的20的准确性,因为这将圆它到的下一个倍数1 / 20 如果你真的希望它四舍五入到两位小数,那么你应该用于accuracy的值是100

您必须将其格式化为String才能执行此操作。 与大多数语言一样,Java将降低尾随零。

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

因此,您可以返回一个String (从double更改返回类型),或者只在需要使用上面的代码显示它时格式化它。 您可以阅读JavaDoc for Formatter ,以了解小数位数,逗号位置等所有可能性。

如果你想要的是String输出,你可以尝试这个

double number = roundOff(1.499);//1.5

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM