有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!


共 (6) 个答案

  1. # 1 楼答案

    乘以100000。加0.5。截断为整数。然后除以100000

    代码:

    double original = 17.77777777;
    int factor = 100000;
    int scaled_and_rounded = (int)(original * factor + 0.5);
    double rounded = (double)scaled_and_rounded / factor;
    
  2. # 2 楼答案

    不管你做什么,如果你最后得到一个double值,它不太可能精确到小数点后5位。这不是二进制浮点运算的工作方式。最好的方法是“将最接近原始值的双精度值四舍五入到小数点后5位”。如果要打印出该双精度的精确值,它可能仍有超过5位小数

    如果确实需要精确的十进制值,则应使用BigDecimal

  3. # 4 楼答案

    您可以将数字乘以第一个小数位,四舍五入到第五个小数位。然后进行正常的四舍五入,并使其再次成为小数点后第五位

    假设要舍入的值是一个名为xdouble

    double factor = 1e5; // = 1 * 10^5 = 100000.
    double result = Math.round(x * factor) / factor;
    

    如果您想要四舍五入到小数点后6位,那么让factor成为1e6,依此类推

  4. # 5 楼答案

    试试下面的方法

    double value = Double.valueOf(String.format(Locale.US, "%1$.5f", 5.565858845));
    
    System.out.println(value); // prints 5.56586
    
    value = Double.valueOf(String.format(Locale.US, "%1$.5f", 5.56585258));
    
    System.out.println(value); // prints 5.56585
    

    或者,如果您需要最少的代码量

    使用导入静态

    import static java.lang.Double.valueOf;
    import static java.util.Locale.US;
    import static java.lang.String.format;
    

    double value = valueOf(format(US, "%1$.5f", 5.56585258));
    

    问候,

  5. # 6 楼答案

    DecimalFormat roundFormatter = new DecimalFormat("########0.00000");
    
    public Double round(Double d)
        {
            return Double.parseDouble(roundFormatter.format(d));
        }