13
countformat
count_format
SYNOPSIS
count_format($n, $point='.', $sep=',', $spacing='')
DESCRIPTION
count_format retourne la représentation sous forme de chaîne de caractères du compteur $n dans un format compact.
Si $n est inférieur à 10000, $n est retourné avec le séparateur de milliers $sep.
Si $n est supérieur ou égal à 10000, $n est arrondi à une décimale avec $point comme séparateur décimal et suffixé par l'unité k ou M séparée par $spacing.
Si $n est négatif, count_format retourne 0.
EXEMPLE
Pour formater un compteur :
php > require 'library/countformat.php';
php > echo count_format(1234, ',', ' ', ' ');
1 234
php > echo count_format(12345, ',', ' ', ' ');
12,3 k
php > echo count_format(1234567, ',', ' ', ' ');
1,2 M
Pour un affichage en anglais :
php > echo count_format(1234);
1,234
php > echo count_format(12345);
12.3k
php > echo count_format(1234567);
1.2M
Un nombre décimal est arrondi :
php > echo count_format(12.34);
12
php > echo count_format(1234.5);
1,235
CODE
- function count_format($n, $point='.', $sep=',', $spacing='') {
- if ($n < 0) {
- return 0;
- }
- if ($n < 10000) {
- return number_format($n, 0, $point, $sep);
- }
- $d = $n < 1000000 ? 1000 : 1000000;
- $f = round($n / $d, 1);
- return number_format($f, $f - intval($f) ? 1 : 0, $point, $sep) . $spacing . ($d == 1000 ? 'k' : 'M');
- }
Commentaires