Jörg Reinholz: Vor dem Komma alles streichen

Beitrag lesen

Moin!

<?php
function numToShortString($n) {
  return preg_replace(array ('/0+$/', '/^0/'), '', sprintf('%f', $n));
}

echo numToShortString(0.34), "\n";
echo numToShortString(0.3), "\n";
echo numToShortString(1.3), "\n";

Da fällt mir ein, dass negative Werte eventuell berücksichtigt werden müssen:

<?php
function numToShortString($n, $german=false) {
  $vorzeichen = ($n < 0 ) ? '-' : '';
  $n=abs($n);
  if (! $german) {
    return $vorzeichen . preg_replace(array ('/0+$/', '/^0/'), '', sprintf('%f', $n));
  } else  {
    return $vorzeichen . str_replace('.', ',' , preg_replace(array ('/0+$/', '/^0/'), '', sprintf('%f', $n)));
  }
}

## Tests
/* 
echo numToShortString(0.34), "\n";
echo numToShortString(0.3), "\n";
echo numToShortString(1.3), "\n";
echo numToShortString(-0.34), "\n";
echo numToShortString(-0.3), "\n";
echo numToShortString(-1.3), "\n";
echo "\n";
echo numToShortString(0.34, true), "\n";
echo numToShortString(0.3, true), "\n";
echo numToShortString(1.3, true), "\n";
echo numToShortString(-0.34, true), "\n";
echo numToShortString(-0.3, true), "\n";
echo numToShortString(-1.3, true), "\n";
# */

Will man noch mehr, dann sollte sich auch number_format() ansehen

Jörg Reinholz