Adds option to multiply decimal percentages. Fixes #3814

This commit is contained in:
Phally 2013-07-09 21:01:55 +02:00
parent 4ded269549
commit e35bd80dfb
3 changed files with 37 additions and 3 deletions

View file

@ -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);
}
/**

View file

@ -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) . '%';
}

View file

@ -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);
}
/**