note 83438 deleted from function.number-format by googleguy
| From: | googleguy@php.net | Date: | Tue, 22 Oct 2013 11:00:33 +0000 |
| Subject: | note 83438 deleted from function.number-format by googleguy | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-197008@lists.php.net to get a copy of this message | ||
Note Submitter: team at glossword dot biz
----
It's pity that the function supports one-byte characters only for "thousands
separator".
For English it works well but for French and Russian it makes problem.
Developers should use character   or chr(0xA0) as "thousands separator" to avoid
the number of being moved to a new line in HTML-documents. But number_format() didn't
understand that symbol.
To solve the problem, we wrote our own variant of number_format():
<?php
/* Replacement for number_format() */
function my_number_format($n, $decimals = 0, $dec_point = ',', $thousands_sep =
' ')
{
$b = explode('.', $n);
$rn = '';
$l = strlen($b[0]);
/* Reverse string */
for ($i = $l; $i > 3; $i -= 3)
{
$rn = $thousands_sep . substr($b[0], $i - 3, 3) . $rn;
}
/* sprintf() used to correct 0.79 to 0.790 */
/* str_replace() used to correct decimals */
/* str_repeat() used to correct decimals */
return substr($b[0], 0, $i) . $rn . ($decimals
? $dec_point.(isset($b[1])
? str_replace('0.', '', sprintf('%0.'.$decimals.'f',
'0.'.$b[1]))
: str_repeat(0, $decimals))
: '');
}
/* Outputs 123 456,790 */
print my_number_format(123456.78987, 3);
?>
It can be optimized more, but this variant works well also.