Search code examples
javabigdecimalcompareto

Simplest way to get the lesser of two BigDecimal values in Java


Is there some way to determine which of two BigDecimal objects is the lower (smaller) number that is simpler than an if or a ternary operator calling BigDecimal::compareTo?

Given:

BigDecimal x = … ;
BigDecimal y = … ;

Either:

if( x.compareTo( y ) < 0 ) {
    return x ;
} else {
    return y ;
} 

Or:

BigDecimal lower = ( x.compareTo( y ) < 0 ) ? x : y ;  // If x is smaller than y, use x. If x is greater than or equal to y, use y. 

Solution

  • Actually, there's a min method in the BigDecimal class.

    BigDecimal min = x.min(y);