Hyperion
Hyperion

Reputation: 2625

Limit decimal digits in Java when using double

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

Answers (3)

Soley
Soley

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

Lumberjack
Lumberjack

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

Karthik Cherukuri
Karthik Cherukuri

Reputation: 633

You can use round for that

double roundedPercentage = (double) Math.round(percentage * 100) / 100;

Upvotes: 3

Related Questions