如何将double加倍到一定数量的小数

时间:2018-03-21 15:50:31

标签: java double rounding

我想调用一个double参数和int精度的函数。

此函数必须使用精度数作为小数来舍入该数字。

示例:function(1.23432, 4)必须将该数字向上舍入为4位小数(1.2343)。任何人都可以帮我解决这个问题吗?

4 个答案:

答案 0 :(得分:0)

试试此代码

String result = String.format("%.2f", 10.0 / 3.0);
// result:  "3.33"

答案 1 :(得分:0)

首先,得到10 precision ,然后将它乘以你的数字,将其四舍五入为int并除以10 precision

public double round(double number, int precision) {
    // 10 to the power of "precision"
    double n = Math.pow(10.0, precision);

    // multiply by "number" and cast to int (round it to nearest integer value)
    int aux = (int) (n * number);

    // divide it to get the result
    return aux / n;
}

然后你打电话:

double result = round(1.23432, 4);
System.out.println(result); // 1.2343

答案 2 :(得分:0)

在对数字进行舍入时,

BigDecimal是你的朋友。您可以指定MathContext以明确设置要舍入的工作方式,然后定义要使用的精度。如果您仍希望在结尾处使用double,则可以致电BigDecimal.doubleValue()

答案 3 :(得分:0)

试试这个:

public String round(double value, int factor) {
    double newFactor = convertFactor(factor);
    //will convert the factor to a number round() can use
    String newVal = Double.toString(Math.round(value / newFactor) * newFactor);
    //the value gets rounded
    return newVal = newVal.substring(0, Math.min(newVal.length(), factor + 2));
    //Convert the result to a string and cut it
    //important because a too high value of the factor or value would cause inaccuracies.
    //factor + 2 because you convert the double into String, and you have to fill 0.0 out
    //Math.min() handles an exception when the factor is higher than the string
}

public double convertFactor(double factor) {
    double newFactor = 1;
    for(int i = 0; i < factor; i++) {
        newFactor /= 10;
        //devide the newFactor as many times as the value of the factor isnt reached
    }

    return newFactor;           
}

使用 convertFactor()将“正常”因子转换为 round()方法可以使用的因子(称为newFactor)。 round()方法计算该值并将其转换为String 最大因素的长度。 太高的价值和因素值会导致不准确,并且这些小的不准确性会被削减以消除它们。

示例代码(针对您的示例):

System.out.println("newFactor: " + convertFactor(4)); //only for test!
System.out.println("Rounded value: " + round(1.23432, 4));

//newFactor: 1.0E-4
//Rounded value: 1.2343
相关问题