Reputation: 553
I have a function that converts 60000 into 60k or 60100 into 60.1k
But if I was to put in for instance 60123, it would output 60.123k
How do I make it output 60.1k without it rounding up like it does for number_format.
EDIT: Here is my function that does the converting
function format($val) {
$letter = "";
while ($val >= 1000) {
$val /= 1000;
$letter .= "K";
}
$letter = str_replace("KKKK", "000B", $letter);
$letter = str_replace("KKK", "B", $letter);
$letter = str_replace("KK", "M", $letter);
return $val.$letter;
}
Here is what I put to echo out
echo format(1)."<br>";
echo format(123548)."<br>";
echo format(1000000)."<br>";
echo format(1000000000)."<br>";
echo format(1200000000)."<br>";
And here is the output:
1
123.548K
1M
1B
1.2B
For the 123.548K, I want it to just be "123.5K"
Upvotes: 1
Views: 2763
Reputation: 3821
Please try the following
function format($val) {
$letter = "";
while ($val >= 1000) {
$val /= 1000;
$letter .= "K";
}
$val = round($val, 1); // it provides the correct format
$letter = str_replace("KKKK", "000B", $letter);
$letter = str_replace("KKK", "B", $letter);
$letter = str_replace("KK", "M", $letter);
return $val.$letter;
}
Upvotes: 1
Reputation: 3500
$value = 123;
echo number_format($value / 1000, 2).'k';
Edit (did not see comment about rounding). Treat the value as a string:
$value = 60146;
$value = $value / 1000;
$value = substr($value, 0, strpos($value, '.')).'.'.substr($value, strpos($value, '.'), 3).'k';
echo $value;
Upvotes: 1
Reputation: 25013
You can use the floor function: http://www.php.net/manual/en/function.floor.php - note that floor(-1.2) = -2, if that could apply.
Upvotes: 2