Vor dem Komma alles streichen
bearbeitet von Jörg ReinholzMoin!
> ~~~ php
> <?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
<?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)));
}
}
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";
~~~
Will man noch mehr, dann sollte sich auch [`number_format()`](http://php.net/manual/de/function.number-format.php) ansehen
Jörg Reinholz
Vor dem Komma alles streichen
bearbeitet von Jörg ReinholzMoin!
> ~~~ php
> <?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
<?php
function numToShortString($n, $german=true) {
$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)));
}
}
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";
~~~
Will man noch mehr, dann sollte sich auch [`number_format()`](http://php.net/manual/de/function.number-format.php) ansehen
Jörg Reinholz