diff --git a/core/model/fieldtypes/Currency.php b/core/model/fieldtypes/Currency.php index b1a840ee7..7c234982c 100644 --- a/core/model/fieldtypes/Currency.php +++ b/core/model/fieldtypes/Currency.php @@ -27,7 +27,16 @@ class Currency extends Decimal { } function setValue($value) { - $this->value = ereg_replace('[^0-9.\-]+','', $value); + $matches = null; + if(is_numeric($value)) { + $this->value = $value; + + } else if(preg_match('/-?\$?[0-9,]+(.[0-9]+)?([Ee][0-9]+)?/', $value, $matches)) { + $this->value = str_replace(array('$',','),'',$matches[0]); + + } else { + $this->value = 0; + } } } diff --git a/tests/fieldtypes/CurrencyTest.php b/tests/fieldtypes/CurrencyTest.php index dd40e9571..161b12f22 100644 --- a/tests/fieldtypes/CurrencyTest.php +++ b/tests/fieldtypes/CurrencyTest.php @@ -4,13 +4,26 @@ class CurrencyTest extends SapphireTest { function testNiceFormatting() { // Test a bunch of different data values and results in Nice() and Whole() $tests = array( + // Test basic operation '$50.00' => array('$50.00', '$50'), + + // Test removal of junk text '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'), + + // Test negative numbers '-1000' => array('($1,000.00)','($1,000)'), - '-$2000' => array('($2,000.00)', '($2,000)'), + '-$2,000' => array('($2,000.00)', '($2,000)'), + + // Test thousands comma '5000' => array('$5,000.00', '$5,000'), + + // Test scientific notation + '5.68434188608E-14' => array('$0.00', '$0'), + '5.68434188608E7' => array('$56,843,418.86', '$56,843,419'), + "Sometimes Es are still bad: 51 dollars, even though they\'re used in scientific notation" => array('$51.00', '$51'), + "What about 5.68434188608E7 in the middle of a string" => array('$56,843,418.86', '$56,843,419'), ); foreach($tests as $value => $niceValues) {