Skip to content

Commit

Permalink
adding CakeNumber::formatDelta() and fixing issue with near-zero valu…
Browse files Browse the repository at this point in the history
…es and format()
  • Loading branch information
euromark committed Sep 19, 2012
1 parent 99cbd22 commit 3fa6b96
Show file tree
Hide file tree
Showing 2 changed files with 96 additions and 28 deletions.
46 changes: 46 additions & 0 deletions lib/Cake/Test/Case/Utility/CakeNumberTest.php
Expand Up @@ -70,6 +70,52 @@ public function testFormat() {
$result = $this->Number->format($value, '-'); $result = $this->Number->format($value, '-');
$expected = '100-100-100'; $expected = '100-100-100';
$this->assertEquals($expected, $result); $this->assertEquals($expected, $result);

$value = 0.00001;
$result = $this->Number->format($value, array('places' => 1));
$expected = '$0.0';
$this->assertEquals($expected, $result);

$value = -0.00001;
$result = $this->Number->format($value, array('places' => 1));
$expected = '$0.0';
$this->assertEquals($expected, $result);
}

/**
* testFormatDelta method
*
* @return void
*/
public function testFormatDelta() {
$value = '100100100';

$result = $this->Number->formatDelta($value, array('before' => '', 'after' => ''));
$expected = '+100,100,100.00';
$this->assertEquals($expected, $result);

$result = $this->Number->formatDelta($value, array('before' => '[', 'after' => ']'));
$expected = '[+100,100,100.00]';
$this->assertEquals($expected, $result);

$result = $this->Number->formatDelta(-$value, array('before' => '[', 'after' => ']'));
$expected = '[-100,100,100.00]';
$this->assertEquals($expected, $result);

$value = 0;
$result = $this->Number->formatDelta($value, array('places' => 1, 'before' => '[', 'after' => ']'));
$expected = '[0.0]';
$this->assertEquals($expected, $result);

$value = 0.0001;
$result = $this->Number->formatDelta($value, array('places' => 1, 'before' => '[', 'after' => ']'));
$expected = '[0.0]';
$this->assertEquals($expected, $result);

$value = 9876.1234;
$result = $this->Number->formatDelta($value, array('places' => 1, 'decimals' => ',', 'thousands' => '.'));
$expected = '+9.876,1';
$this->assertEquals($expected, $result);
} }


/** /**
Expand Down
78 changes: 50 additions & 28 deletions lib/Cake/Utility/CakeNumber.php
Expand Up @@ -70,13 +70,13 @@ class CakeNumber {
/** /**
* Formats a number with a level of precision. * Formats a number with a level of precision.
* *
* @param float $number A floating point number. * @param float $value A floating point number.
* @param integer $precision The precision of the returned number. * @param integer $precision The precision of the returned number.
* @return float Formatted float. * @return float Formatted float.
* @link http://book.cakephp.org/2.0/en/core-libraries/helpers/number.html#NumberHelper::precision * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/number.html#NumberHelper::precision
*/ */
public static function precision($number, $precision = 3) { public static function precision($value, $precision = 3) {
return sprintf("%01.{$precision}F", $number); return sprintf("%01.{$precision}F", $value);
} }


/** /**
Expand Down Expand Up @@ -135,25 +135,25 @@ public static function fromReadableSize($size, $default = false) {
/** /**
* Formats a number into a percentage string. * Formats a number into a percentage string.
* *
* @param float $number A floating point number * @param float $value A floating point number
* @param integer $precision The precision of the returned number * @param integer $precision The precision of the returned number
* @return string Percentage string * @return string Percentage string
* @link http://book.cakephp.org/2.0/en/core-libraries/helpers/number.html#NumberHelper::toPercentage * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/number.html#NumberHelper::toPercentage
*/ */
public static function toPercentage($number, $precision = 2) { public static function toPercentage($value, $precision = 2) {
return self::precision($number, $precision) . '%'; return self::precision($value, $precision) . '%';
} }


/** /**
* Formats a number into a currency format. * Formats a number into a currency format.
* *
* @param float $number A floating point number * @param float $value A floating point number
* @param integer $options if int then places, if string then before, if (,.-) then use it * @param integer $options if int then places, if string then before, if (,.-) then use it
* or array with places and before keys * or array with places and before keys
* @return string formatted number * @return string formatted number
* @link http://book.cakephp.org/2.0/en/core-libraries/helpers/number.html#NumberHelper::format * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/number.html#NumberHelper::format
*/ */
public static function format($number, $options = false) { public static function format($value, $options = false) {
$places = 0; $places = 0;
if (is_int($options)) { if (is_int($options)) {
$places = $options; $places = $options;
Expand All @@ -180,42 +180,64 @@ public static function format($number, $options = false) {
extract($options); extract($options);
} }


$out = $before . self::_numberFormat($number, $places, $decimals, $thousands) . $after; $value = self::_numberFormat($value, $places, '.', '');
$out = $before . self::_numberFormat($value, $places, $decimals, $thousands) . $after;


if ($escape) { if ($escape) {
return h($out); return h($out);
} }
return $out; return $out;
} }


/**
* Formats a number into a currency format to show deltas (signed differences in value).
*
* - `places` - Number of decimal places to use. ie. 2
* - `before` - The string to place before whole numbers. ie. '['
* - `after` - The string to place after decimal numbers. ie. ']'
* - `thousands` - Thousands separator ie. ','
* - `decimals` - Decimal separator symbol ie. '.'
*
* @param float $value A floating point number
* @param array $options
* @return string formatted delta
*/
public static function formatDelta($value, $options = array()) {
$places = isset($options['places']) ? $options['places'] : 0;
$value = self::_numberFormat($value, $places, '.', '');
$sign = $value > 0 ? '+' : '';
$options['before'] = isset($options['before']) ? $options['before'] . $sign : $sign;
return self::format($value, $options);
}

/** /**
* Alternative number_format() to accommodate multibyte decimals and thousands < PHP 5.4 * Alternative number_format() to accommodate multibyte decimals and thousands < PHP 5.4
* *
* @param float $number * @param float $value
* @param integer $places * @param integer $places
* @param string $decimals * @param string $decimals
* @param string $thousands * @param string $thousands
* @return string * @return string
*/ */
protected static function _numberFormat($number, $places = 0, $decimals = '.', $thousands = ',') { protected static function _numberFormat($value, $places = 0, $decimals = '.', $thousands = ',') {
if (!isset(self::$_numberFormatSupport)) { if (!isset(self::$_numberFormatSupport)) {
self::$_numberFormatSupport = version_compare(PHP_VERSION, '5.4.0', '>='); self::$_numberFormatSupport = version_compare(PHP_VERSION, '5.4.0', '>=');
} }
if (self::$_numberFormatSupport) { if (self::$_numberFormatSupport) {
return number_format($number, $places, $decimals, $thousands); return number_format($value, $places, $decimals, $thousands);
} }
$number = number_format($number, $places, '.', ''); $value = number_format($value, $places, '.', '');
$after = ''; $after = '';
$foundDecimal = strpos($number, '.'); $foundDecimal = strpos($value, '.');
if ($foundDecimal !== false) { if ($foundDecimal !== false) {
$after = substr($number, $foundDecimal); $after = substr($value, $foundDecimal);
$number = substr($number, 0, $foundDecimal); $value = substr($value, 0, $foundDecimal);
} }
while (($foundThousand = preg_replace('/(\d+)(\d\d\d)/', '\1 \2', $number)) != $number) { while (($foundThousand = preg_replace('/(\d+)(\d\d\d)/', '\1 \2', $value)) != $value) {
$number = $foundThousand; $value = $foundThousand;
} }
$number .= $after; $value .= $after;
return strtr($number, array(' ' => $thousands, '.' => $decimals)); return strtr($value, array(' ' => $thousands, '.' => $decimals));
} }


/** /**
Expand Down Expand Up @@ -244,14 +266,14 @@ protected static function _numberFormat($number, $places = 0, $decimals = '.', $
* the number will be wrapped with ( and ) * the number will be wrapped with ( and )
* - `escape` - Should the output be htmlentity escaped? Defaults to true * - `escape` - Should the output be htmlentity escaped? Defaults to true
* *
* @param float $number * @param float $value
* @param string $currency Shortcut to default options. Valid values are * @param string $currency Shortcut to default options. Valid values are
* 'USD', 'EUR', 'GBP', otherwise set at least 'before' and 'after' options. * 'USD', 'EUR', 'GBP', otherwise set at least 'before' and 'after' options.
* @param array $options * @param array $options
* @return string Number formatted as a currency. * @return string Number formatted as a currency.
* @link http://book.cakephp.org/2.0/en/core-libraries/helpers/number.html#NumberHelper::currency * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/number.html#NumberHelper::currency
*/ */
public static function currency($number, $currency = 'USD', $options = array()) { public static function currency($value, $currency = 'USD', $options = array()) {
$default = self::$_currencyDefaults; $default = self::$_currencyDefaults;


if (isset(self::$_currencies[$currency])) { if (isset(self::$_currencies[$currency])) {
Expand All @@ -272,14 +294,14 @@ public static function currency($number, $currency = 'USD', $options = array())
$result = $options['before'] = $options['after'] = null; $result = $options['before'] = $options['after'] = null;


$symbolKey = 'whole'; $symbolKey = 'whole';
if ($number == 0 ) { if ($value == 0) {
if ($options['zero'] !== 0 ) { if ($options['zero'] !== 0) {
return $options['zero']; return $options['zero'];
} }
} elseif ($number < 1 && $number > -1 ) { } elseif ($value < 1 && $value > -1) {
if ($options['fractionSymbol'] !== false) { if ($options['fractionSymbol'] !== false) {
$multiply = intval('1' . str_pad('', $options['places'], '0')); $multiply = intval('1' . str_pad('', $options['places'], '0'));
$number = $number * $multiply; $value = $value * $multiply;
$options['places'] = null; $options['places'] = null;
$symbolKey = 'fraction'; $symbolKey = 'fraction';
} }
Expand All @@ -288,10 +310,10 @@ public static function currency($number, $currency = 'USD', $options = array())
$position = $options[$symbolKey . 'Position'] != 'after' ? 'before' : 'after'; $position = $options[$symbolKey . 'Position'] != 'after' ? 'before' : 'after';
$options[$position] = $options[$symbolKey . 'Symbol']; $options[$position] = $options[$symbolKey . 'Symbol'];


$abs = abs($number); $abs = abs($value);
$result = self::format($abs, $options); $result = self::format($abs, $options);


if ($number < 0 ) { if ($value < 0) {
if ($options['negative'] == '()') { if ($options['negative'] == '()') {
$result = '(' . $result . ')'; $result = '(' . $result . ')';
} else { } else {
Expand Down

0 comments on commit 3fa6b96

Please sign in to comment.