有没有办法做一个正则表达式,它在某个点截断一个数字而不四舍五入(简单地将数字舍去?)说在4位数字之后……。它将永远不会处理负数。我可以输入数字,例如0.03123或1.31或10000.98,等等...。我写的到目前为止,我的解决方案是四舍五入而不是我要查找的内容。...
$number = 10000.51999999;
$precision = 4;
echo "<br>";
// grab number before decimal by rounding down the whole number down...
$numberBeforeDecimal = floor($number);
echo "<br>";
// grab the decimal and set the correct precision needed
$n = $number;
intval($n); // 12
$theDecimalPart = explode('.', number_format($n, ($precision)))[1]; // 3430
echo $theDecimalPart; // this is outputting 5200
$theNewValue = $numberBeforeDecimal.".".$theDecimalPart;
答案 0 :(得分:1)
尝试以下(Rextester DEMO):
$number = 10000.51999999;
$precision = 4;
// separate out the integer and decimal part
$number_str_arr = explode('.', $number);
// concatenate them back
$theNewValue = $number_str_arr[0] . '.' . substr($number_str_arr[1], 0, $precision);
echo $theNewValue; // displays 10000.5199