NumberFormatter 返回的值 (PERCENT) 看起来等于测试值,但事实并非如此

问题描述 投票:0回答:1

今天运行 PHPUnit 测试给了我这个奇怪的结果:

There was 1 failure:

1) App\StudioIntern\FormatServiceTest::testNumberToPercent
Failed asserting that two strings are equal.
--- Expected
+++ Actual
@@ @@
-'50 %'
+'50 %'

测试的是这个功能:

public static function numberToPercent(float $value): string
{
    $percent_formatter = \NumberFormatter::create('de_DE', \NumberFormatter::PERCENT);
    return $percent_formatter->format($value);
}

..并以这种方式运行:

$this->assertEquals('50 %', FormatService::numberToPercent(0.5));

使用 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

这很奇怪......感谢您的任何提示!

php number-formatting
1个回答
0
投票

NumberFormatter
使用不可破坏的空格 (U+00A0),因此您可以像这样比较字符串:

$percent_formatter = NumberFormatter::create('de_DE', NumberFormatter::PERCENT);
$value1 = $percent_formatter->format('0.5');
$value2 = "50\u{A0}%";
var_dump($value1==$value2);

演示

© www.soinside.com 2019 - 2024. All rights reserved.