From 397bb5fcc25d90f5456bf19ca9351cde04f1b990 Mon Sep 17 00:00:00 2001 From: Sam Minnee Date: Mon, 17 Mar 2008 02:10:23 +0000 Subject: [PATCH] #2323: Fix casting of negative currency values; add CurrencyTest unit testing git-svn-id: svn://svn.silverstripe.com/silverstripe/open/modules/sapphire/trunk@51145 467b73ca-7a2a-4603-9d3b-597d59a354a9 --- core/model/fieldtypes/Currency.php | 10 +++++++--- tests/fieldtypes/CurrencyTest.php | 24 ++++++++++++++++++++++++ 2 files changed, 31 insertions(+), 3 deletions(-) create mode 100644 tests/fieldtypes/CurrencyTest.php diff --git a/core/model/fieldtypes/Currency.php b/core/model/fieldtypes/Currency.php index ec3ce57c5..b1a840ee7 100644 --- a/core/model/fieldtypes/Currency.php +++ b/core/model/fieldtypes/Currency.php @@ -15,15 +15,19 @@ class Currency extends Decimal { function Nice() { // return "value\">$" . number_format($this->value, 2) . ''; - return '$' . number_format($this->value, 2); + $val = '$' . number_format(abs($this->value), 2); + if($this->value < 0) return "($val)"; + else return $val; } function Whole() { - return '$' . number_format($this->value, 0); + $val = '$' . number_format(abs($this->value), 0); + if($this->value < 0) return "($val)"; + else return $val; } function setValue($value) { - $this->value = ereg_replace('[^0-9.]+','', $value); + $this->value = ereg_replace('[^0-9.\-]+','', $value); } } diff --git a/tests/fieldtypes/CurrencyTest.php b/tests/fieldtypes/CurrencyTest.php new file mode 100644 index 000000000..dd40e9571 --- /dev/null +++ b/tests/fieldtypes/CurrencyTest.php @@ -0,0 +1,24 @@ + array('$50.00', '$50'), + 'this is -50.29 dollars' => array('($50.29)', '($50)'), + 'this is -50.79 dollars' => array('($50.79)', '($51)'), + 'this is 50.79 dollars' => array('$50.79', '$51'), + '-1000' => array('($1,000.00)','($1,000)'), + '-$2000' => array('($2,000.00)', '($2,000)'), + '5000' => array('$5,000.00', '$5,000'), + ); + + foreach($tests as $value => $niceValues) { + $c = new Currency('MyField'); + $c->setValue($value); + $this->assertEquals($niceValues[0], $c->Nice()); + $this->assertEquals($niceValues[1], $c->Whole()); + } + } + +} \ No newline at end of file