how to convert integer to bigdecimal in java

前端 未结 4 598
醉梦人生
醉梦人生 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 15:09

    Google definitely could have helped you, if you know what to look for:

    https://docs.oracle.com/javase/9/docs/api/java/math/BigDecimal.html#BigDecimal-int-

    This is one of the constructors for BigDecimal, which allows you to do the following:

    BigDecimal five = BigDecimal.valueOf(5);
    BigDecimal seven = BigDecimal.valueOf(2).add(five);
    

    Seeing as you stated you wanted to multiply an int and a BigDecimal, this would be achieved as follows:

    BigDecimal result = yourBigDecimal.multiply(BigDecimal.valueOf(yourInt));
    

    And, supposing you want this result as an int:

    int intResult = result.intValue();
    

    Keep in mind that this throws away the fraction though. If you want rounding instead:

    int intResult = result.round(0, RoundingMode.HALF_UP).intValue();
    

提交回复
热议问题