简体   繁体   English

删除小数位而不四舍五入

[英]Remove decimal places without rounding

I have a function that converts 60000 into 60k or 60100 into 60.1k我有一个 function 可以将 60000 转换为 60k 或将 60100 转换为 60.1k

But if I was to put in for instance 60123, it would output 60.123k但是如果我要输入例如 60123,它将是 output 60.123k

How do I make it output 60.1k without it rounding up like it does for number_format.我如何使它成为 output 60.1k 而不是像 number_format 那样四舍五入。

EDIT: Here is my function that does the converting编辑:这是我的 function 进行转换

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:这是 output:

1 1个
123.548K 123.548K
1M 1M
1B 1B
1.2B 1.2B

For the 123.548K, I want it to just be "123.5K"对于 123.548K,我希望它只是“123.5K”

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.您可以使用 floor function: http://www.php.net/manual/en/function.floor.php - 请注意 floor(-1.2) = -2,如果适用的话。

$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;

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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM