Reputation: 93
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.
Upvotes: 1
Views: 1317
Reputation: 32
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;
}
Upvotes: 0
Reputation: 533560
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
Upvotes: 2