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

2

7

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. 
Giralda answered 21/5, 2018 at 5:43 Comment(0)
I
26

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

BigDecimal min = x.min(y);
Inkstand answered 21/5, 2018 at 6:5 Comment(0)
D
8

The API supports it. See BigDecimal.min().

Dumbarton answered 21/5, 2018 at 6:5 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.