java 数字转换bigdeciaml,如何在java中将整数转换为bigdecimal

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 );

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值