简体   繁体   English

在 PHP 中删除尾随零直到小数点后两位

[英]Remove trailing zeros until 2 decimals in PHP

I've tried casting to float and number_format but float will always round at two and number_format is fixed on the amount of decimals you specify.我试过强制转换为floatnumber_format但 float 将始终舍入为 2,而 number_format 固定为您指定的小数位数。

So how can I do this like the following conversion那么我怎样才能像下面的转换一样做到这一点

11.2200 -> 11.22
11.2000 -> 11.20
11.2340 -> 11.234
$money1 = 68.75;
$money2 = 54.35;
$money = $money1 + $money2;
// echo $money will output "123.1";
$formatted = sprintf("%01.2f", $money);
// echo $formatted will output "123.10"

This might help, You can use sprintf given by PHP.这可能会有所帮助,您可以使用 PHP 提供的sprintf

You may use the round() function for this.您可以为此使用 round() 函数。

ie round(number,precision,mode);即轮(数字,精度,模式);

Example:例子:

echo(round(11.2200,2));回声(轮(11.2200,2));

Output输出

11.22 11.22

Thanks谢谢

You can use float casting您可以使用浮动铸造

echo (float) 11.2200;
echo "<br/>";
echo (float) 11.2000;
echo "<br/>";
echo (float) 11.2340;

and you have to check number of digits after decimal point and than get value like below :你必须检查小数点后的位数,然后得到如下值:

$val=(float) 11.2000;
if(strlen(substr(strrchr($val, "."), 1))<2){
    echo number_format($val,2);
} 

Not sure if you need a fix for this anymore, but I just ran into the same problem and here's my solution:不确定您是否需要解决此问题,但我遇到了同样的问题,这是我的解决方案:

$array = array(11.2200, 11.2000, 11.2340);
foreach($array as $x)
{
    // CAST THE PRICE TO A FLOAT TO GET RID OF THE TRAILING ZEROS
    $x = (float)$x

    // EXPLODE THE PRICE ON THE DECIMAL (IF IT EXISTS)
    $pieces = explode('.',$x);

    // IF A SECOND PIECE EXISTS, THAT MEANS THE FLOAT HAS AT LEAST ONE DECIMAL PLACE
    if(isset($pieces[1]))
    {
        // IF THE SECOND PIECE ONLY HAS ONE DIGIT, ADD A TRAILING ZERO TO FORMAT THE CURRENCY
        if(strlen($pieces[1]) == 1)
        {
            $x .= '0';
        }
    }
    // IF NO SECOND PIECE EXISTS, ADD A .00 TO IT TO FORMAT THE CURRENCY VALUE
    else
    {
        $x .= '.00';
    }
}

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

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