From 9e231eb8c88ad9b201217902418c61f8cfbdbc2c Mon Sep 17 00:00:00 2001 From: Vincent Gabriel Date: Sun, 23 Feb 2014 16:23:05 -0800 Subject: [PATCH] added asSize method to format file size #2524 --- framework/base/Formatter.php | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/framework/base/Formatter.php b/framework/base/Formatter.php index d079b5b13d..fcec1d1ce0 100644 --- a/framework/base/Formatter.php +++ b/framework/base/Formatter.php @@ -404,4 +404,30 @@ class Formatter extends Component $ts = isset($this->thousandSeparator) ? $this->thousandSeparator: ','; return number_format($value, $decimals, $ds, $ts); } + + /** + * Formats the value as file size with a unit representation + * @param mixed $value the value to be formatted + * @param integer $decimals the number of digits after the decimal point + * @return string the formatted result + * @see decimalSeparator + * @see thousandSeparator + * @see asNumber + */ + public function asSize($value, $decimals = 0) + { + $units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB']; + $position = 0; + + do { + if ($value < 1024) { + return round($value, $decimals) . $units[$position]; + } + + $value = $value / 1024; + $position++; + } while ($position < count($units)); + + return $this->asNumber($value, $decimals) . Yii::t('yii', end($units)); + } }