简体   繁体   中英

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?

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

您可以为此使用回合

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

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM