java Android Java百分比计算
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5943181/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Android Java percentage calculation
提问by pmc
I can't figure out what's wrong with this code... I'm trying to calculate a percentage:
我无法弄清楚这段代码有什么问题......我正在尝试计算一个百分比:
I'm sure that boath npage and numpages are greater than zero (checked it on the emulator's debug variables inspector), but the resulting cCom is always 0:
我确定boath npage 和numpages 大于零(在模拟器的调试变量检查器上检查过),但结果cCom 始终为0:
Double cCom=(double)(npage/numpages);
tpercent.setText("("+cCom.toString()+"%)");
Any ideas?
有任何想法吗?
回答by thomson_matt
If npage and numpages are both integers, then Java will round (npage/numpages) to an integer (i.e. 0). To make Java do the division with doubles, you need to cast one of the numbers to a double, like this:
如果 npage 和 numpages 都是整数,那么 Java 会将 (npage/numpages) 舍入为整数(即 0)。要让 Java 使用双精度进行除法,您需要将其中一个数字转换为双精度,如下所示:
Double cCom = ((double)npage/numpages);
In fact, because you're working with a percentage, you probably want:
事实上,因为您使用的是百分比,所以您可能想要:
Double cCom = ((double)npage/numpages) * 100;