Browse Source

Adds option to multiply decimal percentages. Fixes #3814

Phally 12 years ago
parent
commit
e35bd80dfb

+ 24 - 0
lib/Cake/Test/Case/Utility/CakeNumberTest.php

@@ -650,6 +650,30 @@ class CakeNumberTest extends CakeTestCase {
 		$result = $this->Number->toPercentage(0, 4);
 		$expected = '0.0000%';
 		$this->assertEquals($expected, $result);
+
+		$result = $this->Number->toPercentage(45, 0, array('multiply' => false));
+		$expected = '45%';
+		$this->assertEquals($expected, $result);
+
+		$result = $this->Number->toPercentage(45, 2, array('multiply' => false));
+		$expected = '45.00%';
+		$this->assertEquals($expected, $result);
+
+		$result = $this->Number->toPercentage(0, 0, array('multiply' => false));
+		$expected = '0%';
+		$this->assertEquals($expected, $result);
+
+		$result = $this->Number->toPercentage(0, 4, array('multiply' => false));
+		$expected = '0.0000%';
+		$this->assertEquals($expected, $result);
+
+		$result = $this->Number->toPercentage(0.456, 0, array('multiply' => true));
+		$expected = '46%';
+		$this->assertEquals($expected, $result);
+
+		$result = $this->Number->toPercentage(0.456, 2, array('multiply' => true));
+		$expected = '45.60%';
+		$this->assertEquals($expected, $result);
 	}
 
 /**

+ 10 - 1
lib/Cake/Utility/CakeNumber.php

@@ -160,12 +160,21 @@ class CakeNumber {
 /**
  * Formats a number into a percentage string.
  *
+ * Options:
+ *
+ * - `multiply`: Multiply the input value by 100 for decimal percentages.
+ *
  * @param float $value A floating point number
  * @param integer $precision The precision of the returned number
+ * @param array $options Options
  * @return string Percentage string
  * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/number.html#NumberHelper::toPercentage
  */
-	public static function toPercentage($value, $precision = 2) {
+	public static function toPercentage($value, $precision = 2, $options = array()) {
+		$options += array('multiply' => false);
+		if ($options['multiply']) {
+			$value *= 100;
+		}
 		return self::precision($value, $precision) . '%';
 	}
 

+ 3 - 2
lib/Cake/View/Helper/NumberHelper.php

@@ -101,11 +101,12 @@ class NumberHelper extends AppHelper {
  *
  * @param float $number A floating point number
  * @param integer $precision The precision of the returned number
+ * @param array $options Options
  * @return string Percentage string
  * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/number.html#NumberHelper::toPercentage
  */
-	public function toPercentage($number, $precision = 2) {
-		return $this->_engine->toPercentage($number, $precision);
+	public function toPercentage($number, $precision = 2, $options = array()) {
+		return $this->_engine->toPercentage($number, $precision, $options);
 	}
 
 /**