如何在java中将整数转换为bigdecimal
我想创建一种计算整数和大十进制乘法的方法. 我在Google和论坛上搜索没有找到我的东西.
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 ;
}
有人可以帮助我吗?
要将整数(或字节/短/浮点数/双精度数)与BigInteger(或BigDecimal)相乘,必须先将本机数字转换为BigInteger/BigDecimal
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.
注意:
valueOf
与new
不同,并且出于不同的原因在 BigInteger . 在这两种情况下,我建议valueOf
胜过new
.
Note:
valueOf
is not the same asnew
, and for different reasons on BigDecimal and BigInteger. In both cases, I recommendvalueOf
overnew
.
我看到您添加了代码,很好.
它不起作用,因为Integer与BigDecimal混合使用,并且*
也不适用于BigDecimal.
如果将其与我的代码进行比较,则修复应该很明显:
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 );
}