Delete digits after two decimal points, without rounding the value

后端 未结 15 1589
死守一世寂寞
死守一世寂寞 2020-11-29 01:04

i have value in php variable like that

$var=\'2.500000550\';
echo $var

what i want is to delete all decimal points after 2 digits.

15条回答
  •  佛祖请我去吃肉
    2020-11-29 01:30

    You're requesting a function that returns "2.50" and not 2.5, so you aren't talking about arithmetic here but string manipulation. Then preg_replace is your friend:

    $truncatedVar = preg_replace('/\.(\d{2}).*/', '.$1', $var);
    
    // "2.500000050" -> "2.50", "2.509" -> "2.50", "-2.509" -> "2.50", "2.5" -> "2.5"
    

    If you want to do it with arithmetic, simply use:

    $truncatedVar = round($var * 100) / 100);
    
    // "2.500000050" -> "2.5", "2.599" -> "2.59", "-2.599" -> "2.59"
    

提交回复
热议问题