简体   繁体   English

使用double时限制Java中的十进制数字

[英]Limit decimal digits in Java when using double

I have a few variables, all int, and I make with them this operation: 我有几个变量,都是int,我用它们做这个操作:

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. 问题是(当然)我得到的结果像65.88841666666666,我想得到一个只有2个十进制数字的数字,我不介意近似它,我也可以将所有数字都切掉,所以我会得到65.88而不是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. 在此,.2表示在小数点后显示2位数字。 For more options, try BigDecimal 有关更多选项,请尝试使用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. 尽管@CHERUKURI的建议是我真正使用的自己,但是当它为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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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