Reputation: 2625
I have a few variables, all int, and I make with them this operation:
percentage = ((double)100) - (((double)100)/(((double)64)*((double)dist.size()-1))*((double)bestDist));
forcing them to be double because I want to calculate a percentage. The problem is that (of course) I get results like 65.88841666666666, and I want to get a number with only 2 decimal digits, I don't mind about approximating it, I can also cut all the digits so I will get 65.88 instead of 65.89. How can I do this?
Upvotes: 2
Views: 5498
Reputation: 1776
Although what @CHERUKURI suggested, is what I really use myself, but it will produce inaccurate result when it is MAX_DOUBLE.
Math.ceil(percentage) + Math.ceil((Math.ceil(percentage) - percentage) * 100)/100.0;
It has too many method calls, however, it will give your what it should.
IF the number is small, then the following is nice enough:
(double) Math.round(percentage * 100) / 100;
Upvotes: 0
Reputation: 91
If this is for displaying result, you can use the formatter like:
String formatted = String.format("%.2f", 65.88888);
Here, .2 means display 2 digits after decimal. For more options, try BigDecimal
Upvotes: 5
Reputation: 633
You can use round for that
double roundedPercentage = (double) Math.round(percentage * 100) / 100;
Upvotes: 3