2

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?

Hyperion
  • 2,515
  • 11
  • 37
  • 59
  • 1
    Do you actually want to change the *value* of `percentage` to only hold 2 digits past the decimal point, or do you want to *display* only the first 2 digits past the decimal point? – azurefrog May 20 '15 at 18:28
  • 1
    possible duplicate of [round up to 2 decimal places in java?](http://stackoverflow.com/questions/11701399/round-up-to-2-decimal-places-in-java) – Jon May 20 '15 at 18:29

3 Answers3

5

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

Lumberjack
  • 91
  • 5
3

You can use round for that

double roundedPercentage = (double) Math.round(percentage * 100) / 100;
Karthik Cherukuri
  • 603
  • 2
  • 9
  • 15
0

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;
Soley
  • 1,716
  • 1
  • 19
  • 33