Created
June 11, 2016 21:12
-
-
Save richjenks/6959b2a84f51c8013b7b2bcb2ab70584 to your computer and use it in GitHub Desktop.
Normalizes a number to within a desired range
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Normalizes a number to within a desired range | |
* | |
* @param int|float $input Number to be normalized | |
* @param int|float $inputMin Lowest number that $input can possibly be | |
* @param int|float $inputMax Highest number that $input can possibly be | |
* @param int|float $outputMin Lower range for desired output | |
* @param int|float $outputMax Upper range for desired output | |
* @param int $precision Optional number of decimal digits to round to | |
* | |
* @return int|float Normalized number | |
*/ | |
function normalize($input, $inputMin, $inputMax, $outputMin, $outputMax, $precision = false) { | |
// Determine ranges | |
$inputRange = $inputMax - $inputMin; | |
$outputRange = $outputMax - $outputMin; | |
// Determine result within desired range | |
$ratio = $inputRange / $outputRange; | |
$output = $input / $ratio + $inputMin; | |
// Round? | |
if ($precision !== false && $precision >= 0) | |
$output = round($output, $precision); | |
// If number has no decimals, convert to int | |
if (intval($output) == $output) | |
$output = intval($output); | |
return $output; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment