Skip to content

Instantly share code, notes, and snippets.

@joelataylor
Last active August 29, 2015 14:19
Show Gist options
  • Save joelataylor/7f2541112870abba64a4 to your computer and use it in GitHub Desktop.
Save joelataylor/7f2541112870abba64a4 to your computer and use it in GitHub Desktop.
OAMM WordPress to Fraction Calculation
public function to_fraction($float) {
$whole = floor( $float );
$decimal = $float - $whole;
if ($decimal == 0) return $whole;
$valid_decimals = array(
'1/8' => 0.125,
'1/4' => 0.25,
'1/3' => 0.333,
'1/2' => 0.5,
'2/3' => 0.666,
'3/4' => 0.75,
'1' => 1
);
asort($valid_decimals);
$fraction = $this->nearest_value($decimal,$valid_decimals);
$fraction = array_search($fraction, $valid_decimals);
return ($whole == 0 ? '' : $whole . ' ') . $fraction;
}
public function nearest_value($value, $array) {
if (array_search($value, $array)) {
return $value;
} else {
$array[] = $value;
sort($array);
$key = array_search($value, $array);
if ($key == 0) { return $array[$key+1]; }
if ($key == sizeof($array)-1) { return $array[$key-1]; }
$dist_to_ceil = $array[$key+1]-$value;
$dist_to_floor = $value-$array[$key-1];
if ($dist_to_ceil <= $dist_to_floor) {
return $array[$key+1];
} else {
return $array[$key-1];
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment