概述
I want to create a method that caculates multiplication an integer and a bigdecimal.
I search on google and forums nothing I found.
import java.math.BigDecimal;
private Integer quantite;
private BigDecimal prixUnit;
public Integer getQuantite() {
return quantite;
}
public void setQuantite(Integer quantite) {
this.quantite = quantite;
}
public BigDecimal getPrixUnit() {
return prixUnit;
}
public void setPrixUnit(BigDecimal prixUnit) {
this.prixUnit = prixUnit;
}
public BigDecimal methCal(BigDecimal quantite, BigDecimal prixUnit){
this.prixUnit=prixUnit;
BigDecimal j = new BigDecimal(quantite);
this.j = quantite;
return quantite*prixUnit ;
}
Can someone help me?
解决方案
To multiply an integer (or byte/short/float/double) with a BigInteger (or BigDecimal), you must convert the native number to BigInteger/BigDecimal first.
// int parameter can be int or Integer
public static BigInteger multiply ( int a, BigInteger b ) {
return BigInteger.valueOf( a ).multiply( b );
}
// BigInteger <> BigDecimal
public static BigDecimal multiply ( int a, BigDecimal b ) {
return BigDecimal.valueOf( a ).multiply( b );
}
// same for add, subtract, divide, mod etc.
Note: valueOf is not the same as new, and for different reasons on BigDecimal and BigInteger.
In both cases, I recommend valueOf over new.
I see that you added your code, nice.
It doesn't work because Integer is mixed with BigDecimal, and also * does not work with BigDecimal.
If you compare it with my code, the fix should be obvious:
public BigDecimal methCal ( int quantite, BigDecimal prixUnit ) {
return BigDecimal.valueOf( quantite ).multiply( prixUnit );
}
最后
以上就是听话猫咪为你收集整理的java 数字转换bigdeciaml,如何在java中将整数转换为bigdecimal的全部内容,希望文章能够帮你解决java 数字转换bigdeciaml,如何在java中将整数转换为bigdecimal所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复