division of bigdecimal by integer

别等时光非礼了梦想. 提交于 2019-12-10 06:56:12

问题


I want to divide a bigdecimal value with an integer.i have rounded the bigdecimal value(if it is 133.333 then rounded value is 133).given below is my code snippet.

v1 = v1.setScale(0, RoundingMode.HALF_UP);
int temp = BigDecimal.valueOf(v1.longValue()).divide(constant1);

value of constant is 12. It is showing an error message that

The method divide(BigDecimal) in the type BigDecimal is not applicable for the arguments (int)

Can anyone help me to do the division?


回答1:


Change

.divide(constant1);

to

.divide(new BigDecimal(constant1));

Btw, why don't you just do something like

int temp = (int) (Math.round(v1.doubleValue()) / constant1);

??




回答2:


You should write the code as follows:

int temp = BigDecimal.valueOf(v1.longValue())
        .divide(BigDecimal.valueOf(constant1)).intValue();

The thing about BigDecimal and BigInteger is that they mostly operate with instances of these classes and not with primitive types. Results of operations are also new instances of these classes.

One other remark: I advise to use valueOf static method instead of a constructor, because by doing this you may have a possibility to avoid creation of new objects. Using a constructor makes creation of a new object explicit, which is not necessary in this case at all.



来源:https://stackoverflow.com/questions/7819553/division-of-bigdecimal-by-integer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!