How to get integer and fraction portions of a BigDecimal in Java

荒凉一梦 提交于 2020-08-09 19:33:23

问题


For a BigDecimal number such as 42.7, how can I tear this apart to get the integer part (42) and the decimal fractional part (0.7)?

I would like to retrieve both as BigDecimal objects. But I will take what I can get and make BigDecimal object from them.


回答1:


setScale()

I think I’d go for setScale().

    BigDecimal bd = new BigDecimal("42.7");
    
    BigDecimal integerPart = bd.setScale(0, RoundingMode.DOWN);
    BigDecimal fractionalPart = bd.subtract(integerPart);
    
    System.out.println(integerPart);
    System.out.println(fractionalPart);
42
0.7

It seems to me to be clear to read.




回答2:


tl;dr

myBigDecimal
.divideAndRemainder( BigDecimal.ONE )
[ 0 ]                                    // for integer part

…and…

[ 1 ]                                    // for fraction part

BigDecimal::divideAndRemainder

The BigDecimal class offers some methods for this.

The BigDecimal::divideAndRemainder method divides your original number by another number. The result is an array of two BigDecimal objects, the first being the integer portion and the second being the fraction amount.

To achieve your goal, we merely need to divide by one. The BigDecimal class offers a constant object for the value of one: BigDecimal.ONE.

BigDecimal input = new BigDecimal( "42.7" ) ;
BigDecimal[] parts = input.divideAndRemainder( BigDecimal.ONE );

Dump to console.

System.out.println( Arrays.toString( parts ) );

[42.0, 0.7]

Grab each piece from the array.

BigDecimal input = new BigDecimal( "42.7" ) ;
BigDecimal[] parts = input.divideAndRemainder( BigDecimal.ONE );
BigDecimal integerPart = parts[ 0 ] ;
BigDecimal fractionPart = parts[ 1 ] ;

If you only need one part:

  • myBigDecimal.divideAndRemainder( BigDecimal.ONE )[ 0 ] integer part
  • myBigDecimal.divideAndRemainder( BigDecimal.ONE )[ 1 ] fraction part

Addition puts them together again.

BigDecimal humptyDumpty = integerPart.add( fractionPart ) ;


来源:https://stackoverflow.com/questions/63085009/how-to-get-integer-and-fraction-portions-of-a-bigdecimal-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!