2014-02-08 13 views
-2

У меня есть число с плавающей запятой в PHP: 0.966666666667 Я хотел бы напечатать это нравится: 0.96 Я использовал круглый() и number_format(), но они дают мне как 0.97 есть функция, чтобы сделать это, пожалуйста, ?PHP две цифры после запятой

+3

Пожалуйста исследуйте перед вопросом: http://stackoverflow.com/questions/4668628/truncate-float-numbers-with-php –

ответ

1

Вы можете сделать это:

$num = 0.966666; 
$num = floor($num * 100)/100; 
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

Смежные вопросы