diff --git a/src/Formatter/CurrencyFormatter.php b/src/Formatter/CurrencyFormatter.php index 8d4d11f2..a006d0ae 100644 --- a/src/Formatter/CurrencyFormatter.php +++ b/src/Formatter/CurrencyFormatter.php @@ -8,6 +8,7 @@ use CommerceGuys\Intl\Exception\UnknownCurrencyException; use CommerceGuys\Intl\NumberFormat\NumberFormat; use CommerceGuys\Intl\NumberFormat\NumberFormatRepositoryInterface; +use CommerceGuys\Intl\Calculator; /** * Formats currency amounts using locale-specific patterns. @@ -97,6 +98,7 @@ public function format($number, $currencyCode, array $options = []) throw new InvalidArgumentException($message); } + $negative = (Calculator::compare('0', (string) $number, 12) == 1); $this->validateOptions($options); $options = array_replace($this->defaultOptions, $options); $numberFormat = $this->getNumberFormat($options['locale']); @@ -117,8 +119,9 @@ public function format($number, $currencyCode, array $options = []) $number = str_replace('¤', $currency->getCurrencyCode(), $number); } else { // No symbol should be displayed. Remove leftover whitespace. - $number = str_replace('¤', '', $number); - $number = trim($number, " \xC2\xA0"); + $negative_sign = $negative ? $numberFormat->getMinusSign() : ''; + $pattern = '/^' . $negative_sign . '¤*\s*(.*?)\s*¤*$/us'; + $number = preg_replace($pattern, $negative_sign . '$1', $number); } return $number; diff --git a/tests/Formatter/CurrencyFormatterTest.php b/tests/Formatter/CurrencyFormatterTest.php index 9e80a519..9ef267e2 100644 --- a/tests/Formatter/CurrencyFormatterTest.php +++ b/tests/Formatter/CurrencyFormatterTest.php @@ -8,6 +8,7 @@ use CommerceGuys\Intl\Formatter\CurrencyFormatter; use CommerceGuys\Intl\NumberFormat\NumberFormat; use CommerceGuys\Intl\NumberFormat\NumberFormatRepository; +use CommerceGuys\Intl\Tests\NumberFormat\CustomNumberFormatRepository; /** * @coversDefaultClass \CommerceGuys\Intl\Formatter\CurrencyFormatter @@ -184,6 +185,17 @@ public function testParse($locale, $currencyCode, $number, $expectedNumber) $this->assertSame($expectedNumber, $parsedNumber); } + /** + * @covers ::format + */ + public function testFormatUtf8() + { + include __DIR__ . '/../NumberFormat/CustomNumberFormatRepository.php'; + $numberFormatRepository = new CustomNumberFormatRepository(); + $formatter = new CurrencyFormatter($numberFormatRepository, new CurrencyRepository()); + $this->assertSame("\xc2\xb1950.00", $formatter->format('-950.000000', 'USD', ['currency_display' => 'none', 'locale' => 'tst'])); + } + /** * Provides the number format, currency format, number style, value and expected formatted value. */ diff --git a/tests/NumberFormat/CustomNumberFormatRepository.php b/tests/NumberFormat/CustomNumberFormatRepository.php new file mode 100644 index 00000000..7f98aad7 --- /dev/null +++ b/tests/NumberFormat/CustomNumberFormatRepository.php @@ -0,0 +1,23 @@ + "\xc2\xb1", + ]; + return $return; + } +}