Java 百分比

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18034813/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 21:56:29  来源:igfitidea点击:

Java percent of number

java

提问by user2622574

Is there any way to calculate (for example) 50% of 120? I tried:

有没有办法计算(例如)120 的 50%?我试过:

int k = (int)(120 / 100)*50;

But it doesn't work.

但它不起作用。

采纳答案by Lake

int k = (int)(120 / 100)*50;

The above does not work because you are performing an integer division expression (120 / 100) which result is integer 1, and then multiplying that result to 50, giving the final result of 50.

上述方法不起作用,因为您正在执行整数除法表达式 (120 / 100),其结果为整数 1,然后将该结果乘以 50,最终结果为 50。

If you want to calculate 50% of 120, use:

如果要计算 120 的 50%,请使用:

int k = (int)(120*(50.0f/100.0f));

more generally:

更普遍:

int k = (int)(value*(percentage/100.0f));

回答by Eric Urban

int k = (int)(120*50.0/100.0);

回答by Patricia Shanahan

I suggest using BigDecimal, rather than float or double. Division by 100 is always exact in BigDecimal, but can cause rounding error in float or double.

我建议使用 BigDecimal,而不是 float 或 double。在 BigDecimal 中除以 100 总是精确的,但可能会导致 float 或 double 的舍入错误。

That means that, for example, using BigDecimal 50% of x plus 30% of x plus 20% of x will always sum to exactly x.

这意味着,例如,使用 BigDecimal 的 x 的 50% 加上 x 的 30% 加上 x 的 20% 将总和正好是 x。

回答by venkat balabhadra

Never use floating point primitive types if you want exact numbers and consistent results, instead use BigDecimal.

如果您想要精确的数字和一致的结果,请不要使用浮点原始类型,而是使用 BigDecimal。

The problem with your code is that result of (120/100) is 1, since 120/100=1.2 in reality, but as per java, int/int is always an int. To solve your question for now, cast either value to a float or double and cast result back to int.

您的代码的问题是 (120/100) 的结果是 1,因为实际上 120/100=1.2,但根据 java,int/int 始终是 int。要暂时解决您的问题,请将值转换为 float 或 double 并将结果转换回 int。

回答by Lore Lai

Division must be float, not int

除法必须是浮点数,而不是整数

(120f * 50 / 100f)

(120f * 50 / 100f)

回答by Peter Lawrey

You don't need floating point in this case you can write

在这种情况下你不需要浮点数,你可以写

int i = 120 * 50 / 100;

or

或者

int i = 120 / 2;

回答by Konstantin F

it is simple as 2 * 2 = 4 :)

很简单 2 * 2 = 4 :)

int k = (int)(50 * 120) / 100;