running a PHPUnit test today gave me this strange result:
There was 1 failure:
1) App\StudioIntern\FormatServiceTest::testNumberToPercent
Failed asserting that two strings are equal.
--- Expected
+++ Actual
@@ @@
-'50 %'
+'50 %'
The test is on this function:
public static function numberToPercent(float $value): string
{
$percent_formatter = \NumberFormatter::create('de_DE', \NumberFormatter::PERCENT);
return $percent_formatter->format($value);
}
..and runs this way:
$this->assertEquals('50 %', FormatService::numberToPercent(0.5));
Same result when using the CLI:
php > $percent_formatter = \NumberFormatter::create('de_DE', \NumberFormatter::PERCENT);
php > $value1 = $percent_formatter->format('0.5');
php > $value2 = '50 %';
php > echo $value1;
50 %
php > echo $value2;
50 %
php > echo ($value1 === $value2) ? 'equal' : 'not equal';
not equal
This is weird... Thanks for any hint!
NumberFormatter
uses a non-breakable space (U+00A0), so you can compare the strings like this:
$percent_formatter = NumberFormatter::create('de_DE', NumberFormatter::PERCENT);
$value1 = $percent_formatter->format('0.5');
$value2 = "50\u{A0}%";
var_dump($value1==$value2);
(demo)