how to convert integer to bigdecimal in java

前端 未结 4 602
醉梦人生
醉梦人生 2020-12-09 14:46

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.BigDecim         


        
4条回答
  •  天涯浪人
    2020-12-09 14:53

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

提交回复
热议问题