Java Clamp clamp(final T MIN, final T MAX, final T VALUE)

Here you can find the source of clamp(final T MIN, final T MAX, final T VALUE)

Description

clamp

License

Apache License

Declaration

public static final <T extends Number> T clamp(final T MIN,
            final T MAX, final T VALUE) 

Method Source Code

//package com.java2s;
/*/*from w  ww.  ja v  a  2s .  co m*/
 * Copyright (c) 2016 by Gerrit Grunwald
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

public class Main {
    public static final <T extends Number> T clamp(final T MIN,
            final T MAX, final T VALUE) {
        if (VALUE.doubleValue() < MIN.doubleValue())
            return MIN;
        if (VALUE.doubleValue() > MAX.doubleValue())
            return MAX;
        return VALUE;
    }

    public static final int clamp(final int MIN, final int MAX,
            final int VALUE) {
        if (VALUE < MIN)
            return MIN;
        if (VALUE > MAX)
            return MAX;
        return VALUE;
    }

    public static final long clamp(final long MIN, final long MAX,
            final long VALUE) {
        if (VALUE < MIN)
            return MIN;
        if (VALUE > MAX)
            return MAX;
        return VALUE;
    }

    public static final double clamp(final double MIN, final double MAX,
            final double VALUE) {
        if (Double.compare(VALUE, MIN) < 0)
            return MIN;
        if (Double.compare(VALUE, MAX) > 0)
            return MAX;
        return VALUE;
    }
}

Related

  1. clamp(final short value, final short lower, final short upper)
  2. clamp(final T MIN, final T MAX, final T VALUE)
  3. clamp(T min, T val, T max)
  4. clamp(T n, T l, T h)
  5. clamp(T value, T minimum, T maximum)
  6. clamp01(long value)