3

I have a numeric value myX that I want to bound to some range [X_MIN, X_MAX]. I don't care whether myX is within that range or not, I just want to make it so.

Obviously this works:

if(myX < X_MIN) {
  myX = X_MIN;
} else if (myX > X_MAX) {
  mX = X_MAX;
}

as does this:

myX = Math.max(X_MIN, Math.min(myX, X_MAX));

The first is too verbose and the meaning of the second isn't immediately obvious. Is there another simple, explicit way to do this? Solutions using Guava, Commons, etc are welcome.

Travis Christian
  • 2,412
  • 2
  • 24
  • 41
  • 5
    related: http://stackoverflow.com/questions/16656651/does-java-have-a-clamp-function – aioobe Jun 22 '15 at 17:04
  • 2
    Ah, "clamp" - that's why my search didn't return anything useful. – Travis Christian Jun 22 '15 at 17:07
  • 1
    Guava recently introduced [`Ints.constrainToRange()`](https://google.github.io/guava/releases/snapshot/api/docs/com/google/common/primitives/Ints.html#constrainToRange-int-int-int-) to address this. – dimo414 Mar 23 '17 at 05:52

0 Answers0