Restricts a value to be within a specified range. - Java java.lang

Java examples for java.lang:Math Value

Description

Restricts a value to be within a specified range.

Demo Code


//package com.java2s;

public class Main {
    /**/*from   w ww  .  ja  v a 2s. com*/
     * Restricts a value to be within a specified range.
     * 
     * @param value
     *        The value to clamp.
     * @param min
     *        The minimum value. If {@code value} is less than {@code min}, {@code min} will be
     *        returned.
     * @param max
     *        The maximum value. If {@code value} is greater than {@code max}, {@code max} will be
     *        returned.
     * @return The clamped value.
     */
    public static float clamp(float value, float min, float max) {
        // First we check to see if we're greater than the max
        value = (value > max) ? max : value;

        // Then we check to see if we're less than the min.
        value = (value < min) ? min : value;

        // There's no check to see if min > max.
        return value;
    }

    /**
     * Restricts a value to be within a specified range.
     * 
     * @param value
     *        The value to clamp.
     * @param min
     *        The minimum value. If {@code value} is less than {@code min}, {@code min} will be
     *        returned.
     * @param max
     *        The maximum value. If {@code value} is greater than {@code max}, {@code max} will be
     *        returned.
     * @return The clamped value.
     */
    public static int clamp(int value, int min, int max) {
        value = (value > max) ? max : value;
        value = (value < min) ? min : value;
        return value;
    }
}

Related Tutorials