Search code examples
phpnumber-formattingmultibyte

How to format numbers with thin space as a thousand separator?


Instead of displaying numbers formatted like this:

1,234,567.890, I want to display numbers formatted like this:

1 234 567.890, which is slightly different from this:
1 234 567.890.

I am using the PHP function:

number_format($value, 0, ".", " ")

But, it produces this:

1�234�567.890

I have already set the http header and the html document to UTF-8. I believe this problem arises due to the thin space being a multi-byte character. I have not been able to find a mb string function that deals with this.

Does anyone has an idea of how to deal with this problem?


Solution

  • 5.4.0 This function now supports multiple bytes in dec_point and thousands_sep. Only the first byte of each separator was used in older versions.

    http://php.net/number_format

    Based on that, here's a very hacky fix for the problem in older PHP versions, short of rolling your own implementation of number_format:

    $separator = ' ';
    echo preg_replace('/(?<=\d)\x' . bin2hex($separator[0]) . '(?=\d)/',
                      $separator,
                      number_format($value, 0, '.', $separator));