1

I'm working on a calculator in Java but the "." buttons function won't work. if I remove the Math.round() I sometimes get 1.1999999 instead of 1.2. How do I solve this problem? I've tried looking up several Math.round() solutions on stack overflow but none of them worked.

x = Math.round(x + (y / (Math.pow(10, z)) * 1000) / (double) 1000);

the code above is what I've tried so far.

Paul T. Rawkeen
  • 3,994
  • 3
  • 35
  • 51
F.johansson
  • 83
  • 14
  • At rounding issues you can also take a look into this question: [How to resolve a Java Rounding Double issue](http://stackoverflow.com/questions/179427/how-to-resolve-a-java-rounding-double-issue) – asdf Nov 02 '16 at 15:14
  • How are you displaying your double? eg. 1.2 might be represented as something closer to 1.1999999. – matt Nov 02 '16 at 15:14

2 Answers2

2

You have to round the solution before dividing.

double d = x + y / Math.pow(10, z);
double r = Math.round(d * 1e3) / 1e3; // round to 3 decimal places
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
0

you can try format your text using NumberFormat class

public String formatNumber(int n){
    NumberFormat f= NumberFormat.getInstance();
    f.setMinimumFractionDigits(2);// minimum digits after comma
    f.setMaximumFractionDigits(2);//maximum digits after comma
    String formattedN = f.format(n);
    return formattedN;
}