0

What I'm trying to do is take the user given input (operand) and round my current number to the amount of decimals that the operand is. For example if my current number in the calculator program this is running on is 15.44876, and the user input is 2, I would like the returned value to be 15.45, or just 15.44 at least.

public double round(double operand){
    this.answer = Math.round(this.answer, operand);
    return this.answer;

I know the code above is incorrect, but it's just a place holder since I'm pretty confused on this.

  • 2
    Does this answer your question? [How to round a number to n decimal places in Java](https://stackoverflow.com/questions/153724/how-to-round-a-number-to-n-decimal-places-in-java) – jrook Feb 07 '20 at 21:07

1 Answers1

1

You can multiply by the appropriate power of 10, round, and then divide by the same power of 10. This approach assumes that the numbers are in ranges such that overflow will not be a problem.

public double round(double value, int places) {
    final double scale = Math.pow(10.0, places);
    return Math.round(value * scale) / scale;
}

If overflow might be an issue, there are other approaches.

Ted Hopp
  • 232,168
  • 48
  • 399
  • 521