PHP dropping decimals without rounding up

前端 未结 13 2161
独厮守ぢ
独厮守ぢ 2020-12-09 15:09

I want to drop off decimals without rounding up. For example if I have 1.505, I want to drop last decimal and value should be 1.50. Is there such a function in PHP?

相关标签:
13条回答
  • 2020-12-09 15:30

    Use the PHP native function bcdiv

    echo bcdiv(2.56789, 1, 2);  // 2.56
    
    0 讨论(0)
  • 2020-12-09 15:35

    You need floor() in this way:

    $rounded = floor($float*100)/100;
    

    Or you cast to integer:

    $rounded = 0.01 * (int)($float*100);
    

    This way it will not be rounding up.

    0 讨论(0)
  • 2020-12-09 15:36

    you can convert 1.505 to String data type and make use of substring() to truncate last character.
    And again convert it in integer.

    0 讨论(0)
  • 2020-12-09 15:36
    $num = 118.74999669307;
    $cut = substr($num, 0, ((strpos($num, '.')+1)+2));`
    // Cut the string from first character to a length of 2 past the decimal.
    / substr(cut what, start, ( (find position of decimal)+decimal itself)+spaces after decimal) )
    echo $cut; 
    

    this will help you shorten the float value without rounding it..

    0 讨论(0)
  • 2020-12-09 15:41

    We can use bc functions if they are available:

    echo bcadd(sprintf('%F', 5.445), '0', 2); // => 5.44
    echo sprintf('%.2F', 5.445); // => 5.45
    
    0 讨论(0)
  • 2020-12-09 15:44
    $float = 1.505;
    
    echo sprintf("%.2f", $float);
    
    //outputs 1.50
    
    0 讨论(0)
提交回复
热议问题