0

I want to call a function with a double parameter and an int precision.

This function would have to round that number with the precision number as decimals.

Example: function(1.23432, 4) would have to round that number up with 4 decimals (1.2343). Could anyone help me out with this?

studx
  • 39
  • 3

4 Answers4

0

Try this code

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

First, you get 10precision, then you multiply it by your number, round it to an int and divide by 10precision:

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

Then you call:

double result = round(1.23432, 4);
System.out.println(result); // 1.2343
studx
  • 39
  • 3
0

BigDecimal is your friend when it comes to rounding numbers. You can specify a MathContext to explicitly set how you want you rounding to work, and then define the precision you want to use. If you still want a double at the end you can call BigDecimal.doubleValue()

Brad
  • 15,186
  • 11
  • 60
  • 74
0

Try this:

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

Use convertFactor() to convert your "normal" factor into a factor (called newFactor) the round() method can use. The round() method calculates the value and convert it into a String which the max. lengh of the factor. Too high values of value and factor would cause inaccuracies, and this little inaccuracies get cutted to get rid of them.

Example code (for your example):

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
Lucas M.
  • 1
  • 4