PHP小数点后的两个数字

时间:2014-02-08 17:51:25

标签: php numbers

我在PHP中有一个浮点数:0.966666666667 我想将它打印成:0.96我使用了round()和number_format(),但它们都给了我两个 0.97有这样的功能吗?

2 个答案:

答案 0 :(得分:1)

你可以这样做:

$num = 0.966666;
$num = floor($num * 100) / 100;

答案 1 :(得分:0)

我发现这样做的最好方法是:

//$val - the value to truncate
//$dist - the number of digits after to decimal place to keep
function truncate($val, $dist) {
    //get position of digit $dist places after decimal point
    $pos = strpos($val,'.');

    if($pos !== false) {//if $val is actually a float

        //get the substring starting at the beginning
        //and ending with the point $dist after the
        //decimal, inclusive -- convert to float.
        $val = floatval(substr($val, 0, $pos + 1 + $dist));

    }          

    return $val;
}

然后拨打truncate($YOUR_NUM, 2);

来源:https://stackoverflow.com/a/12710283/3281590