【问题标题】:Comparing PHP's NumberFormatter::formatCurrency results比较 PHP 的 NumberFormatter::formatCurrency 结果
【发布时间】:2015-10-02 22:56:38
【问题描述】:

我在对使用 NumberFormatter::formatCurrency 的库进行单元测试时遇到问题。经过反复试验,我将问题缩小到这个测试用例:

/**
 * @dataProvider getLocales()
 */
public function test($locale, $expected)
{
    $number_formatter = new \NumberFormatter($locale, \NumberFormatter::CURRENCY);
    $actual = $number_formatter->formatCurrency(3000.05, 'EUR');
    $this->assertEquals($expected, $actual, $locale.' failed');
}

public function getLocales()
{
    return array(
        array('en_US', '€3,000.05'),
        array('fr_FR', '3 000,05 €'),
        array('de_DE', '3.000,05 €'),
    );
}

结果是:

fr_FR failed
Failed asserting that two strings are equal.
Expected :3 000,05 €
Actual   :3 000,05 €


de_DE failed
Failed asserting that two strings are equal.
Expected :3.000,05 €
Actual   :3.000,05 €

如你所见,失败的测试似乎有相同的字符串,所以应该是语言环境的问题。

我尝试过与 strcoll 进行比较,在比较之前设置语言环境,以及其他没有运气的组合。

我猜这与每种语言中不同的 utf-8 代码有关。但是那我该如何比较这些字符串呢?

【问题讨论】:

  • 为了通过测试,我实际上必须回显 $actual 结果,然后从 dataProvider 复制并粘贴预期值。但在我看来,这不是一个可接受的解决方案。
  • 是的,问题是空间是用不同的编码编码的......而不是十六进制值 20 你得到 a0
  • 我知道这个问题有点老了,但实际上我在使用 NumberFormatter 时遇到了类似的问题。我能够破译的是,截至目前,NumberFormatter::formatCurrency() 实际上正在返回一个包含隐藏字符的字符串,因此它们看起来相同但实际上具有不同的字符串长度。通过utf8encode 运行预期和实际结果,我能够找到这一点。不幸的是,我还没有找到一个干净的解决方案。你能想出一个吗?
  • 我做了我在第一条评论中解释的事情,然后我就忘记了。抱歉,我无法提供更多帮助。
  • @GrahamS.,您是否同时找到了解决方案?我目前正在努力解决同样的问题。

标签: php utf-8 locale number-formatting currency-formatting


【解决方案1】:

我找到了解决方案。 PHP 的 NumberFormatter 插入了一个特殊的空格字符,即所谓的 No-Break-Space(也许你知道 )。

如果你转换读取值

str_replace("\xc2\xa0", " ", $actual);

一切都会好起来的。

【讨论】:

    猜你喜欢
    • 2013-10-27
    • 2015-07-10
    • 1970-01-01
    • 1970-01-01
    • 2020-05-08
    • 2019-07-29
    • 2017-06-17
    • 2019-10-26
    • 1970-01-01
    相关资源
    最近更新 更多