Created
October 9, 2013 12:05
-
-
Save lennartvdd/6900211 to your computer and use it in GitHub Desktop.
Round values to nearest multiple's of {n} and/or to an arbitrary precision (number of decimals)
This file contains 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 | |
/** | |
* Created by: Lennart van den Dool <lennartvdd at gmail.com> | |
*/ | |
Class SomeModel | |
{ | |
/** | |
* @var integer The number of decimals to round to | |
* | |
* Default: 2 | |
*/ | |
public $round_precision = 2; | |
/** | |
* @var integer In which direction to perform the rounding: | |
* - -1: floor | |
* - 0: round | |
* - 1: ceil | |
* | |
* Default: 0 | |
*/ | |
public $round_precision_direction = 0; | |
/** | |
* @var integer @see round()'s $mode parameter (http://nl3.php.net/round). | |
* | |
* Default: PHP_ROUND_HALF_UP | |
*/ | |
public $round_mode = PHP_ROUND_HALF_UP; | |
/** | |
* @var integer Round to the nearest mutliple of {n} | |
*/ | |
public $round_to_nearest_multiple; | |
/** | |
* @var integer Round up, down or normal to the nearest multiple of {n} | |
* | |
* Default: 0 | |
*/ | |
public $round_to_nearest_multiple_direction = 0; | |
/** | |
* Rounds a value to an arbitrary precision, using the options specified above. | |
* - -1: round down (uses: floor() | |
* - 0: default (uses: round(), rounds halves up) | |
* - 1: round up (uses: ceil()) | |
* | |
* @param float $value | |
* @return float | |
*/ | |
public function roundValue($value) { | |
if($this->round_to_nearest_multiple > 0) | |
{ | |
if($this->round_to_nearest_multiple_direction < 0) { | |
//round down | |
$value = floor($value * $this->round_to_nearest_multiple) / $this->round_to_nearest_multiple; | |
} elseif($this->round_to_nearest_multiple_direction > 0) { | |
//round up | |
$value = ceil($value * $this->round_to_nearest_multiple) / $this->round_to_nearest_multiple; | |
} else { | |
//round normal | |
$value = round($value * $this->round_to_nearest_multiple) / $this->round_to_nearest_multiple; | |
} | |
} | |
if($this->round_precision > 0) { | |
$value = round($value, $this->round_precision, $this->round_mode); | |
} | |
return $value; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment